-1

First one returns an array of objects . Every object has a unique user id which I need in order to call the second service.

this._vendorService.getAllPickupLoc().subscribe(val => {
  val.forEach(element => {
    this.finalObject = element;
    this._vendorService.getVendorUserInfo(element.id).subscribe(res => {
      this.finalObject["userInfo"] = res;
      this.finalArray.push(this.finalObject);
    });
  });
});

While it works fine, there are two drawbacks to the code above. 1. It’s starting to look like callback hell. 2. I’d have to handle the disposal of every subscription by myself.

1 Answers1

1

You can chain these together using RxJS operators:

this._vendorService.getAllPickupLoc().pipe(
  // emit each element in order
  mergeMap(elements => from(elements)),
  // subscribe to inner Observable for each element and emit result
  mergeMap(element => this._vendorService.getVendorUserInfo(element.id)),
  // handle info
  tap(userInfo => {
    this.finalObject["userInfo"] = res;
    this.finalArray.push(this.finalObject);
  })
).subscribe();

Depending on the structure of the rest of your code, you could even get rid of the tap and simply map each emission and add toArray to emit the final result as an array.

Will Alexander
  • 3,425
  • 1
  • 10
  • 17