【发布时间】:2020-10-07 14:07:14
【问题描述】:
为确保错误不会完成 outer observable,我采用的常见rxjs effects 模式是:
public saySomething$: Observable<Action> = createEffect(() => {
return this.actions.pipe(
ofType<AppActions.SaySomething>(AppActions.SAY_SOMETHING),
// Switch to the result of the inner observable.
switchMap((action) => {
// This service could fail.
return this.service.saySomething(action.payload).pipe(
// Return `null` to keep the outer observable alive!
catchError((error) => {
// What can I do with error here?
return of(null);
})
)
}),
// The result could be null because something could go wrong.
tap((result: Result | null) => {
if (result) {
// Do something with the result!
}
}),
// Update the store state.
map((result: Result | null) => {
if (result) {
return new AppActions.SaySomethingSuccess(result);
}
// It would be nice if I had access the **error** here.
return new AppActions.SaySomethingFail();
}));
});
请注意,如果底层网络调用失败 (service.saySomething(action.payload)),我在 inner observable 上使用 catchError 来保持 outer observable 活动: p>
catchError((error) => {
// What can I do with error here?
return of(null);
})
随后的tap 和map 运算符通过允许null(即(result: Result | null))在其签名中适应这一点。但是,我丢失了错误信息。最终,当最终的 map 方法返回 new AppActions.SaySomethingFail(); 时,我丢失了有关错误的任何信息。
我怎样才能在整个管道中保留错误信息,而不是在被捕获时丢失它?
【问题讨论】:
-
你就不能
return of(error);吗? -
@józef-podlecki 我可以,但是我如何在
tap和map中区分错误和成功结果? -
这似乎会导致错误
tap((result: Result | null) => result is Result {是警告A function whose declared type is neither 'void' nor 'any' must return a value.ts(2355)。
标签: rxjs ngrx ngrx-effects rxjs-observables