【问题标题】:Always call the second API in flatMap总是调用 flatMap 中的第二个 API
【发布时间】:2020-10-19 22:30:00
【问题描述】:

我正在调用 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);
});

【问题讨论】:

    标签: angular rxjs observable angular8 flatmap


    【解决方案1】:

    您应该将您的 catchError 呼叫移到 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);
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      • 1970-01-01
      • 2017-09-28
      • 2019-11-30
      • 2022-07-03
      • 1970-01-01
      相关资源
      最近更新 更多