使用带有http observable的rxjs遇到麻烦

问题描述

我正在做一个简单的http调用获取对象数组

getFruit():Observable<Fruit[]> {
    return this.http.get<Fruit[]>(URL);
}

水果对象是

export class Fruit {
    public name: string;
    public color: string;
}

当我尝试对管道进行分组或执行任何操作时,问题代码如下:

fruitService.getFruit().pipe(
  groupBy(f => f.color),mergeMap(group => group.pipe(toArray()))
);

但是当我尝试使用rxjs groupBy时出现错误

Property 'color' does not exist on type 'Fruit[]'

解决方法

groupBy每个发出的值起作用,当您使用http客户端时,它将发出一个值,一个数组以及它本身的数组,没有颜色属性

如果您希望按颜色对结果进行分组,则只需像对任何数组一样映射它即可。

一种方法是使用Array.reduce,例如:

this.fruits$ = this.fruitService.getFruit().pipe(
  map(fruits => {
    const key = 'color';

    return fruits.reduce((allFruits,fruit) => {
        (allFruits[fruit[key]] = allFruits[fruit[key]] || []).push(fruit);
        return allFruits;
      },{});
  })  
)

stackblitz live example

*从here

复制简化的实现