Reputation: 10838
I do have a number of urls. Some of these urls may fail, some may not.
I want to run requests one by one
or all at the same time
to figure-out which one will succeed to proceed with its result up on the chain.
Using forkJoin
might be a potential solution that will run all requests simultaneously, but if any requests will fail the forkJoin is failing.
private getData() {
const url1 = myUrl1;
const url2 = myUrl2;
forkJoin([this.http.get<Data>(url1), this.http.get<Data>(url2)]).pipe(
)
return successfulReultHere
}
Do you have any ideas how to solve that?
Upvotes: 1
Views: 54
Reputation: 1729
You can still use forkJoin
with individual catchError
operators for each of the apis like below -
private getData$() {
const url1 = `myUrl1`;
const url2 = `myUrl2`;
return forkJoin([
this.http.get<Data>(url1).pipe(catchError(e => of('Error in url1'))),
this.http.get<Data>(url2).pipe(catchError(e => of('Error in url2')))
]);
}
Even if one of the apis fail, the error will be caught in the respective catchError which will return a new observable, so that it won't impact other API observable results.
Upvotes: 1
Reputation: 12196
i would suggest this solution
private getData() {
const url1 = myUrl1;
const url2 = myUrl2;
return merge([
this.http.get<Data>(url1).pipe(catchError(() => EMPTY)),
this.http.get<Data>(url2).pipe(catchError(() => EMPTY))
]).pipe(
first()
)
}
here we merge both of the "sources" and the first result that succeds goes straing to output. we also ignore the errors and any other results. also first()
will make sure that error will be emmited if there is not a single success during http calls
Upvotes: 2