我已将以下代码段发送给代码审查。这种效果需要在请求调用之后分派成功操作,或者如果服务方法抛出错误,则分派错误操作,这非常标准。
@Effect()
fetchData$ = this.actions$.pipe(
ofType(ActionTypes.FetchData),
switchMap(() => {
return this.dataService.fetchData().pipe(
map((data: IData): StoreAction<IData> =>
new FetchDataSuccess(data)),
catchError((error) => of(addErrorValue(error, ErrorCode.FETCH_DATA)))
)};
));
但是,外部开发人员给了我评论(我没有联系,因此无法要求澄清)。他指示我用另一个switchMap包装我的switchMap(如下面的代码),因为上面代码中第一个switchMap内部的catch错误“将导致效果中断”。
@Effect()
fetchData$ = this.actions$.pipe(
switchMap((a: StoreAction<IType>) => of(a).pipe(
ofType(ActionTypes.FetchData),
switchMap(() => {
return this.dataService.fetchData().pipe(
map((data: IData): StoreAction<IData> =>
new FetchDataSuccess(data)),
);
}),
catchError((error) => of(addErrorValue(error, ErrorCode.FETCH_DATA)))
))
);
<我不了解,我所缺少的是:为什么我们将switchMap包装到另一个switchMap中?在第一种情况下与第二种情况下,有人可以解释这个特殊可观察的工作流程吗?
您在内部可观察物(catchError
)上有一个this.dataService.fetchData
就足够了。如果此处发生错误,则由catchError
处理,并且效果将调度操作addErrorValue(error, ErrorCode.FETCH_DATA)
。
您可以在NgRx example app中看到相同的模式
请参阅https://blog.strongbrew.io/safe-http-calls-with-rxjs/和https://medium.com/city-pantry/handling-errors-in-ngrx-effects-a95d918490d9了解更多信息