简体   繁体   中英

trouble using rxjs with http observable

I am doing a simple http call and getting an array of objects

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

the fruit object is

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

the problem code is below when i try to group or do anything in the pipe:

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

however when i try to use rxjs groupBy i get errors;

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

groupBy acts on each emitted value, when you use http client it will emit one value, an array, and the array it self, does not have a color property

If you wish to group results by color you only need to map it just as you would with any array.

One way to do it would be using Array.reduce , something like:

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

*copied reduce implementation from here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM