0

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!!

iBlehhz
  • 566
  • 5
  • 26

1 Answers1

1

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]) => { ... });
Community
  • 1
  • 1
  • hey @trichetriche thanks for your help! How if I have some logic to execute for quoteService? (I've updated my question, where it says "execute code using code") – iBlehhz Jan 14 '19 at 10:51
  • 1
    @iBlehhz I have updated my answer with the `tap` operator –  Jan 14 '19 at 10:57