当可观察物位于另一个可观察物内时抛出错误

时间:2019-08-29 08:28:06

标签: angular typescript rxjs observable

当内部可观察到的执行完成时,控制转到错误块。

我的组件服务层-控件转到错误块。

   this.ApplicationService.getPageData(id).subscribe((DataObj)=>{
      console.log(DataObj);
   },
   (error)=>{
      console.log('Failed to get data.'); <-- The control comes here
   })

在我的应用程序服务层中-

    return this.dbService.queryData(req).pipe(mergeMap((r)=>{
        if(r!=null) {
           let key : string = r.other_id;
           return dbService.queryOtherSource(key).pipe(map((r1)=> {
                    if(r1) {
                        obj = do some data processing
                        return of(obj); <-- Control comes here.
                    }
                },
                (err)=> {
                    throw err;
                }));
            }            
        },
        (error)=>{
            throw error;
        }));

1 个答案:

答案 0 :(得分:0)

MergeMap和Map不接受错误处理。您正在使用mergeMap参数resultSelector抛出您看到的错误。

有一个特定的运算符来处理它们。在需要时抛出错误(使用rxjs抛出新的错误或throwError())。如果需要在Observable链中的特定位置处理它,请在管道中使用运算符catchError()

有关此错误处理的有效演示,请参见此stackblitz: https://stackblitz.com/edit/angular-h88bjo

在没有添加任何信息的情况下也没有必要抛出错误。从引发错误的那一刻起,如果没有发现错误,它将传播到顶层。