Search code examples
angularrxjsobservableangular9mergemap

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[]'

Solution

  • 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