-1

I am making calls to API1 and API2. The result obtained from API1 is passed to the call of API2. If the call to API1 fails, API2 should be called with a blank value.

this.Api1().pipe(flatMap(result => { 
 return this.Api2(result);
 })).subscribe( data => {
     console.log('Successfully called api 2', data);
});

How should I ensure that API2 will always be called even if call to Api1 fails.

this.Api1().pipe(flatMap(result => { 
 return this.Api2(result);
 }),
   catchError((err: any) => {
      console.log('call to api1 failed');
      return this.Api2(''); // but the subscribe wont run 
    }))
  ).subscribe( data => {
     console.log('Successfully called api 2', data);
});
Malwaregeek
  • 2,274
  • 3
  • 15
  • 18

1 Answers1

1

You should move your catchError call before flatMap:

this.Api1().pipe(
  catchError((err: any) => {
    console.log('call to api1 failed');
    return of(''); // no need to pass this.Api2 here, just emit blank value, flatMap will take it
  }),
  flatMap(result => {
    return this.Api2(result);
  }))
  .subscribe(data => {
    console.log('Successfully called api 2', data);
  });
Mladen
  • 2,070
  • 1
  • 21
  • 37