将NgRx Action作为函数参数时应使用何种类型?
NgRx Effects错误处理封装的类型问题
在我的NgRx Effects中,我采用了如下结构处理请求错误,确保两点:
- 错误由state/store处理
- 错误被传递给全局错误处理器/拦截器
原始Effects代码:
getItems$ = createEffect((): Observable<Action> => { return this.action$.pipe( ofType(ItemActions.getItem), exhaustMap(() => { return this.apiClient.getItems().pipe( map((response) => ItemActions.getItemsSuccess({ response })), catchError((exception: HttpErrorResponse) => of(EMPTY).pipe( tap(() => this.store.dispatch(ItemActions.getItemsFailure({ exception }))), switchMap(() => throwError(() => exception)), ), ), ); }), ); });
因为每次处理错误都要写这5行重复代码,我把它封装成了一个通用方法:
handle(action: Function, error: HttpErrorResponse, props?: object): Observable<never> { return of(EMPTY).pipe( tap(() => this.store.dispatch(action({ exception: error, ...(props && { ...props }) }))), switchMap(() => throwError(() => error)), ); }
现在catchError可以简化成这样:
catchError((error: HttpErrorResponse) => this.errors.handle(ItemActions.getItemsFailure, error)),
这段代码能正常运行,但有两个类型相关的问题需要解决:
action参数的正确类型应该是什么?目前用Function能跑,但不符合TypeScript的类型规范props参数的正确类型应该是什么?目前用object能跑,但应该只允许传入对应Action定义的合法props
内容的提问来源于stack exchange,提问作者Jeffrey Roosendaal
相关产品推荐
相关产品推荐

