You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将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)),

这段代码能正常运行,但有两个类型相关的问题需要解决:

  1. action参数的正确类型应该是什么?目前用Function能跑,但不符合TypeScript的类型规范
  2. props参数的正确类型应该是什么?目前用object能跑,但应该只允许传入对应Action定义的合法props

内容的提问来源于stack exchange,提问作者Jeffrey Roosendaal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 04:44:54