Handle error in forkJoin on subscribe

2019-08-02 01:54发布

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.

2条回答
聊天终结者
2楼-- · 2019-08-02 02:32

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

查看更多
混吃等死
3楼-- · 2019-08-02 02:36

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
    })
查看更多
登录 后发表回答