Christopher You
Christopher You

Reputation: 63

Triple nested rxjs subscription. Having trouble w/ mergeMap

When I try using mergeMap, the debugger doesn't trigger in its expression. I have to call these api's one after another.

this.apiService.httpGet(API_URLS.getStats"/statistics?lang=en&region=us").pipe(first()).subscribe((teamStats: any) => {
this.apiService.httpGet(API_URLS.getATS').pipe(first()).subscribe((atsPayload: any) => {
this.apiService.httpGet(API_URLS.getGameHistory").pipe(first()).subscribe((gameHistory: any) => {
      })
    })
  })
})

Upvotes: 0

Views: 158

Answers (1)

RomainG
RomainG

Reputation: 597

1: If you want to make 3 simultaneous call and use their result, you can use forkjoin followed by switchMap:

forJoin([
  this.apiService.httpGet(API_URLS.getStats/statistics?lang=en&region=us),
  this.apiService.httpGet(API_URLS.getATS),
  this.apiService.httpGet(API_URLS.getGameHistory)
]).pipe(
  switchMap(([result1, result2, result3])=> this.apiService.httpGet('finalCall', result1, result2, result3))
).subscribe((finalResult) => {});

2: I you need the previous call result for the next one :

this.apiService.httpGet(API_URLS.getStats"/statistics?lang=en&region=us").pipe(
  switchMap((result1) => this.apiService.httpGet(API_URLS.getATS)),
  switchMap((result2) => this.apiService.httpGet(API_URLS.getGameHistory))
).subscribe((result3) => {})

3: I the last 2 calls depends onthe result of the first call :

this.apiService.httpGet(API_URLS.getStats/statistics?lang=en&region=us).pipe(
  switchMap((stats) => forkJoin([
    of(stats),
    this.apiService.httpGet(API_URLS.getATS),
    this.apiService.httpGet(API_URLS.getGameHistory)
]))
)
.subscribe([stats, secondCall, thirdCall]);

Upvotes: 1

Related Questions