Angular-RxJs ForkJoin如何在发生错误后仍继续多个请求 [英] Angular - RxJs ForkJoin How To Continue Multiple Requests Even After A Error

查看:76
本文介绍了Angular-RxJs ForkJoin如何在发生错误后仍继续多个请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了使用不同的参数外,我多次查询单个API端点.无论出于何种原因,其中一些请求都可能失败并返回500错误.如果他们这样做,我仍然希望其他请求继续进行,并向我返回所有成功请求的数据.

I am querying a single API endpoint multiple times except with different parameters. For what ever reason some of these requests may fail and return a 500 error. If they do i still want the other requests to carry on and return me the data of all the successfull requests.

let terms = [];
terms.push(this.category.category);
terms = terms.concat(this.category.interests.map((x) => x.category));

for (let i = 0; i < terms.length; i++) {

    const params = {
        term: terms[i],
        mode: 'ByInterest'
    };


    const request = this.evidenceService.get(this.job.job_id, params).map((res) => res.interactions);

    this.requests.push(request);

}

const combined = Observable.forkJoin(this.requests);

combined.subscribe((res) => {
    this.interactions = res;
});

推荐答案

最简单的方法是将每个请求与 catch 链接起来,该请求仅发出 null :

Most easily chain each request with catch that emits just null:

const request = this.evidenceService.get(...)
  .map(...)
  .catch(error => Observable.of(null)); // Or whatever you want here

失败的请求在结果数组中仅具有 null 值,该数组将由 forkJoin 发出.

The failed requests will have just null value in the resulting array that will be emitted by forkJoin.

请注意,在这种情况下您不能使用 Observable.empty(),因为 empty()不会发出任何内容,只是在 forkJoin 要求所有源Observable至少发出一个值.

Note that you can't use Observable.empty() in this situation because empty() doesn't emit anything and just completes while forkJoin requires all source Observables to emit at least one value.

这篇关于Angular-RxJs ForkJoin如何在发生错误后仍继续多个请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆