Search code examples
angularhttpsubscribeswitchmap

(Angular 2/4/5/6) Two (or more) inner subscribe methods and one outer subscribe method


I'm trying to figure out how do I call 2 inner subscribe methods with an outer subscribe method. In total I would like to do 3 api calls, however, 2 api calls are dependent on the results of 1 api call.

this.subscription = this.quoteService //1st api call
    .get(this.quoteid)
    .pipe(
    switchMap((q: TradeinQuote) => {
        const quote = q["quote"];
        //execute code using quote
        this.price = quote["price"];
        this.retrieveDeviceid = quote["deviceid"];
        return this.faultService.get(this.retrieveDeviceid); //2nd api call
        }),
    ).subscribe(
        (faultGroup: FaultGroup[]) => {
        //execute logic for 2nd api call
    });
);

So after I have gotten this.retrieveDeviceid from the 1st api call, I would like to make another 2 api calls, one of them on faultService (as shown) and the second one on deviceService

E.g. this.deviceService.get(this.retrieveDeviceid)

Currently the code shown only handles 1 inner subscribe and 1 outer subscribe. In order to do another inner subscribe, do I have to use a mergeMap or forkJoin and how do I go about doing it? Appreciate your guidance!!


Solution

  • Use siwtchMap and forkJoin :

    this.subscription = this.quoteService.get(this.quoteid).pipe(
      switchMap(response => forkJoin(
        of(response),
        this.faultService.get(response.quote.deviceid),
        this.deviceService.get(response.quote.deviceid),
      ))
    ).subscribe(([res1, res2, res3]) => { ... });
    

    forkJoin combines the results of cold observables (i.e. observables that don't emit values anymore).

    EDIT

    To manage some logic for a single call, you can use tap :

    this.subscription = this.quoteService.get(this.quoteid).pipe(
      tap(response => { /* execute some code with your first HTTP call response */ }),
      switchMap(response => forkJoin(
        of(response),
        this.faultService.get(response.quote.deviceid),
        this.deviceService.get(response.quote.deviceid),
      ))
    ).subscribe(([res1, res2, res3]) => { ... });