0

I need your help in RxJS.

I made this code, that's needed to fetch an API, and for returned element, get this element type from another API. This code works fine, but it return an Observable for 'type' property instead of "string" only. Do you know how to achieve this? Thanks a lot.

combineLatest([
  this.service.list().pipe(
   map(items =>
     items.map(item => {
       item['type'] = this.getType(item.id);
       return item;
     })
    ),
    map(items => items.map(item => ({
      id: item.id,
      type: item['type'],
    })))
 ),
 this.form.valueChanges,
]).subscribe()

1 Answers1

1

You're assigning the Observable to the property instead of it's response. You'd need to use RxJS forkJoin and Array#map with a higher order mapping operator like switchMap.

Try the following

combineLatest([
  this.service.list().pipe(
    switchMap((items: any) =>             // <-- switch to another observable
      forkJoin(                           // <-- multiple parallel requests
        items.map(item => 
          this.getType(item['id']).pipe(
            map((type: any) => ({         // <-- map back to original item with added type
              ...item,
              type: type
            }))
          )
        )
      )
    )
  ),
  this.form.valueChanges,
]).subscribe()
ruth
  • 29,535
  • 4
  • 30
  • 57
  • Hi @Michael, thanks for your response it looks so good, I have a question why you choose to use the fork-join operator while we didn't have a parallel API call need as i seed in the question code? – Rebai Ahmed Apr 16 '21 at 09:06
  • 1
    @RebaiAhmed: The requirement _"fetch a property for each object in a array"_ is a standard use-case for parallel requests. Essentially the independent properties are fetched in parallel. But if it creates a performance bottleneck (due to too many requests) you could replace the `forkJoin` with `from + concatMap` to fetch the properties sequentially. You could also see [here](https://stackoverflow.com/a/62872189/6513921) for a buffered fetching routine. – ruth Apr 16 '21 at 09:18
  • Thanks for your reply, it learns me a lot – Rebai Ahmed Apr 16 '21 at 09:29