Handle error in forkJoin on subscribe

旧巷老猫 提交于 2019-12-11 12:15:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!