首页 > 解决方案 > rxjs:如何从 catchError 中返回另一个 observable 的结果

问题描述

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

这是我到目前为止所拥有的。我想我需要使用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);

有人可以帮忙吗?

标签: angularrxjs

解决方案


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

      // 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运算符只会在可观察对象引发错误时触发,并且由于您希望对每个调用进行不同的错误处理,因此可以这样做。

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

请查看提供的 stackblitz 以查看实际情况:

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


推荐阅读