[Fixed] Angular Map and Subscribe in Observable pipe

Issue

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()

Solution

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()

Leave a Reply

(*) Required, Your email will not be published