问题
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