Angular - RxJs ForkJoin How To Continue Multiple Requests Even After A Error

走远了吗. 提交于 2020-05-13 04:56:05

问题


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

回答1:


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

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

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.




回答2:


You could use rxjs catchError :

const request = this.evidenceService.get(this.job.job_id, params)
.pipe(map((res) => res.interactions),
catchError(error => of(undefined)));


来源:https://stackoverflow.com/questions/50129965/angular-rxjs-forkjoin-how-to-continue-multiple-requests-even-after-a-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!