繁体   English   中英

rxjs:如何从 catchError 返回另一个可观察的结果

[英]rxjs: how to return the result from another observable from catchError

我正在使用 rxjs 6.5 和 angular。 基本上,我想在我的服务中有一个方法:

  • 如果 api 响应,则从第一个 api 调用返回状态
  • 如果第一个调用失败,则从第二个(不同的)api 调用返回状态
  • 如果第二次调用失败,则返回一个虚拟值

这是我到目前为止所拥有的。 我想我需要使用flatMap/mergeMap ,但我不知道如何使用。

服务.ts

public getStatus()
  {
    return this.http.get('http://api.com/status1')
      .pipe(
        catchError(() => {
            //makes 2nd api call here
            return this.http.get('http://api.com/status2')

            .pipe(catchError(() =>
            {
              //both calls failed
              return of({
                  data: 'blah',
                  success: false
                });

            }))

        }));
  }

组件.ts

this.service.getStatus().subscribe(status=>this.status = status);

有人可以帮忙吗?

您的方法有效,但嵌套管道看起来不太好。 不过,您可以做一件简单的事情:

      // Use 'of' operator to "fake" a successful API call.
      // Use 'throwError' operator to "fake" a failed API call.
      public getStatus()
      {
        return of('firstApiCall')
          .pipe(
            catchError(() => {
              //makes 2nd api call here
              return of('secondApiCall')
            }),
            catchError(() =>
              {
                //both calls failed
                return of({
                    data: 'blah',
                    success: false
                  });
              })
          );
      }

您可以提取第二个catchError块以将所有运算符都放在一个级别上 - catchError运算符只会在 observable 引发错误时触发,并且由于您希望对每次调用进行不同的错误处理,因此可以这样做。

可能你也可以只用一个catchError块来处理它,并对请求 URL 进行一些检查以确定你想要返回什么,但我想这需要更多的逻辑并且不值得。

请查看提供的 stackblitz 以查看其实际效果:

https://stackblitz.com/edit/angular-rfevnt

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM