I want to run some requests in parallel using forkJoin
and combine their results as shown below.
However, when one of the requests fails, the rest of the subscriptions are automatically cancelled by the browser. What is a simple alternative to forkJoin
that lets me run requests in parallel and if one subscription fails, the rest are allowed to complete?
const posts = this.http.get("https://myApi.com/posts?userId=1");
const albums = this.http.get("https://myApi.com/albums?userId=1");
forkJoin([posts, albums]).subscribe((result) => {
this.print(result[0], result[1]);
});
print(res1, res2) {
const message = res1.text res2.text;
console.log(message);
}
CodePudding user response:
You can achieve that using forkJoin
, however, you have to handle the errors for each sub Observable
separately using catchError
to prevent canceling the stream if any error occurred.
You can try something like the following:
// import { catchError } from 'rxjs/operators';
// import { forkJoin, of } from 'rxjs';
const posts = this.http
.get('https://myApi.com/posts?userId=1')
.pipe(catchError((err) => of(err)));
const albums = this.http
.get('https://myApi.com/albums?userId=1')
.pipe(catchError((err) => of(err)));
forkJoin([posts, albums]).subscribe((result) => {
this.print(result[0], result[1]);
});