Angular 始终在flatMap中调用第二个API

Angular 始终在flatMap中调用第二个API,angular,rxjs,observable,angular8,flatmap,Angular,Rxjs,Observable,Angular8,Flatmap,我正在给API1和API2打电话。从API1获得的结果被传递给API2的调用。如果对API1的调用失败,则应使用空值调用API2 this.Api1().pipe(flatMap(result => { return this.Api2(result); })).subscribe( data => { console.log('Successfully called api 2', data); }); 如何确保即使调用Api1失败,API2也始终被调用 this

我正在给API1和API2打电话。从API1获得的结果被传递给API2的调用。如果对API1的调用失败,则应使用空值调用API2

this.Api1().pipe(flatMap(result => { 
 return this.Api2(result);
 })).subscribe( data => {
     console.log('Successfully called api 2', data);
});
如何确保即使调用Api1失败,API2也始终被调用

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);
});

您应该在
flatMap
之前移动
catchError
调用:

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);
  });