【问题标题】:Handle error in forkJoin on subscribe在订阅时处理 forkJoin 中的错误
【发布时间】:2018-06-20 08:44:48
【问题描述】:

我有下一个功能:

   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']);
     })
    }

在这种情况下我该如何处理错误?实际上,在我的所有承诺都解决后,我只需要使用thencatch,所以对我来说根本不是使用forkJoin

【问题讨论】:

    标签: angular promise rxjs fork-join


    【解决方案1】:

    forkJoin 如果 any(至少一个)Observables 它是 fork-joining 抛出错误,则会抛出错误。您可以在错误处理程序中处理它:

    Observable
        .forkJoin(promises).subscribe(() => {
            this.messagesService.createMessage('success', `Saved`);
            this.router.navigate(['/dashboard/my-calculations']);
        },
        (error) => {
            //handle your error here
        }, () => {
            //observable completes
        })
    

    【讨论】:

      【解决方案2】:

      你可以做如下代码

      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 
          );
        }
      

      基本上使用catchError操作符,它会为你做的

      在此处查看详细信息:Way to handle Parallel Multiple Requests

      【讨论】:

        猜你喜欢
        • 2020-03-29
        • 1970-01-01
        • 2017-11-25
        • 2017-08-08
        • 2017-08-01
        • 1970-01-01
        • 2019-01-25
        • 2014-03-05
        • 1970-01-01
        相关资源
        最近更新 更多