【问题标题】:rxjs: how to return the result from another observable from catchErrorrxjs:如何从 catchError 中返回另一个 observable 的结果
【发布时间】:2020-01-20 11:49:01
【问题描述】:

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

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

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

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

            }))

        }));
  }

component.ts

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

有人可以帮忙吗?

【问题讨论】:

标签: angular rxjs


【解决方案1】:

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

      // 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

【讨论】:

  • 谢谢。实际上问题是我在第二次 API 调用中有一个 map,而在那个 map 中我返回的是 of(value) 而不是 value 本身......你的堆栈闪电帮助我找出问题
  • 这个问题的经验法则是:如果使用switchMap - 你需要返回一个可观察的如果使用map - 你需要返回一个“不可观察”的值
猜你喜欢
  • 1970-01-01
  • 2021-02-05
  • 1970-01-01
  • 1970-01-01
  • 2019-08-05
  • 1970-01-01
  • 2021-03-06
  • 2021-12-20
  • 2018-09-15
相关资源
最近更新 更多