![](/img/trans.png)
[英]Getting error when calling a method inside observable which returns another observable
[英]Error being thrown when observable is inside another observable
当内部 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;
}));
您不能将错误处理函数传递给mergeMap
和map
(并且如果您只是想抛出错误,则不必这样做)。 当前,您正在传递一个函数,该函数将一个错误作为第二个参数传递给mergeMap
,这是不建议使用的resultSelector
,因此每个值都将映射为throw error
,然后终止Observable并最终返回错误回调。
我认为您的代码可能如下所示:
return this.dbService.queryData(req).pipe(
filter(Boolean), // filter out 'undefined', 'null', 'false'
mergeMap(r => {
let key: string = r.other_id;
return dbService.queryOtherSource(key).pipe(
filter(Boolean),
map(r1 => {
obj = do some data processing
return obj; // don't use 'of' inside of 'map'
})
);
})
);
MergeMap和Map不接受错误处理。 您正在使用mergeMap参数resultSelector
抛出看到的错误。
有专门的操作员来处理它们。 在需要时抛出错误(使用rxjs抛出新的Error或throwError()
)。 如果需要在Observable链中的特定位置处理它,请在管道中使用运算符catchError()
。
请参阅此stackblitz,以获取基于您的代码的错误处理的有效演示: https ://stackblitz.com/edit/angular-h88bjo
如果不添加任何信息,也不会抛出错误。 从引发错误的那一刻起,如果未发现错误,它将传播到顶层。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.