angular - RxJs zip 运算符,检查哪一个抛出错误并根据条件继续?

标签 angular error-handling rxjs observable rxjs6

我有 2 个 api 服务调用,我将它们压缩到一个可观察对象中:

const firstAPIrequest = this.firstApi.getData();
const secondAPIrequest = this.secondApi.getData();

const combined = zip(firstAPIrequest, secondAPIrequest);

我目前映射这些以返回一个数组:

combined.pipe(
   map((res) => {
      return [res[0], res[1]) // just an example
   }
);

然后我将其用作不同组件中的订阅

combined.subscribe(
   (res) => this.handleData(res),
   (err) => {
      console.debug('Fetch failed', err);
   }
)

在这种情况下,如果其中一个 API 请求失败,它将显示错误,但我想检查哪一个 API 请求失败,例如;如果 request1 返回数据并且 request2 失败,我仍然会从 request1

返回数据

我尝试过catchError,但我认为我无法获取此函数中的数据

combined.pipe(
   catchError((err) => ...), // how would I catch the data before it throws an error?
   map((res) => {
      return [res[0], res[1]) // just an example
   }
);

最佳答案

要单独处理来自每个源的错误,必须将 catchError 分别通过管道传输到每个源。 catchError 必须返回一个可观察对象,因此我们将使用 RxJS of 函数来实现它。

import { of, catchError } from 'rxjs';

const handleError = (error: any) => of({error: error});

const firstAPIrequest = this.firstApi.getData().pipe(
  catchError(this.handleError)
);
const secondAPIrequest = this.secondApi.getData().pipe(
  catchError(this.handleError)
);

const combined = zip(firstAPIrequest, secondAPIrequest);

现在,在订阅中您可以检查响应是否有效或错误。

combined.subscribe(
  ([res1, res2]) => {
    if (!!res1.error && !!res2.error) {
      // both API calls threw error
    } else if (!!res1.error) {
      // `firstAPIrequest` threw error
    } else if (!!res2.error) {
      // `secondAPIrequest` threw error
    } else {
      // both returned responses
    }
  }
);

注意:这假设实际响应不包含属性错误。如果是这样,请将 handleError 函数中的 error 属性替换为其他内容。

关于angular - RxJs zip 运算符,检查哪一个抛出错误并根据条件继续?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70111414/

相关文章:

angular - 使用 angular2-logger 显示行号和文件名

javascript - Angular 4 从 API 响应中获取 header

node.js - 无法将属性 'username'设置为null

ruby - 如何从Ruby方法中删除多重 yield ?

javascript - RxJS v5 : How to make a POST request with params?

Angular 4 找不到名称 'ViewChild'

node.js - 在 Mean.js 中使用 Node 的域

ajax - Angular/RxJS 我应该取消订阅每个 ajax 调用吗?

angular - 如何在 Angular 中正确实现 ngOnDestroy()?

angular - 如何将货币管道与 ngx-translate 一起使用?