问题
I have next function:
saveTable() {
...
let promises = [];
for (index = 0; index < this._TOTAL.length; ++index) {
let promise = this.db.object(ref).update(this._TOTAL[index]);
promises.push(promise);
}
Observable.forkJoin(promises).subscribe(() => {
this.messagesService.createMessage('success', `Saved`);
this.router.navigate(['/dashboard/my-calculations']);
})
}
How can i handle error in this case? Actually, i just need to use then
and catch
after all my promises resolve, so using forkJoin
for me not fundamentally.
回答1:
forkJoin
will throw an error if any (at least one) of the Observables
it is fork-joining throws an error. You can handle it at your error handler:
Observable
.forkJoin(promises).subscribe(() => {
this.messagesService.createMessage('success', `Saved`);
this.router.navigate(['/dashboard/my-calculations']);
},
(error) => {
//handle your error here
}, () => {
//observable completes
})
回答2:
you can do code as below
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
import { forkJoin } from 'rxjs/observable/forkJoin';
forkJoinTest() {
const prouctIds: number[] = [1, 2, 3];
const productRequests = prouctIds.map(id => this.productService.getProduct(id).pipe(
catchError(error => of(`Bad Promise: ${error.message}`))
));
const requests = forkJoin(productRequests);
requests.subscribe(
data => console.log(data) //process item or push it to array
);
}
bascially make use of catchError
operator , it will do for you
Check for detail here : Way to handle Parallel Multiple Requests
来源:https://stackoverflow.com/questions/50943949/handle-error-in-forkjoin-on-subscribe