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

2

14

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;
});
Billow answered 2/5, 2018 at 8:15 Comment(0)
C
11

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.

Conduction answered 2/5, 2018 at 8:50 Comment(1)
See "catchError" in other answer https://mcmap.net/q/393565/-angular-rxjs-forkjoin-how-to-continue-multiple-requests-even-after-a-error for the "newer" rxjs version, where you have to use pipe() instead of chaining...Sumption
R
5

You could use rxjs catchError :

const request = this.evidenceService.get(this.job.job_id, params)
.pipe(map((res) => res.interactions),
catchError(error => of(undefined)));
Rachal answered 2/5, 2018 at 8:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.