You need to enable JavaScript to run this app. 如何在NGRX Effects的switchMap后tap函数中获取原始Action的props参数
优惠活动
大模型
产品
解决方案
定价
更多

如何在NGRX Effects的switchMap后tap函数中获取原始Action的props参数

NGRX Effect中获取原始Action参数的实现方案

问题本质

你当前在switchMap外层的tap拿到的是switchMap返回的successLoad action,自然找不到原始updateCustomer action里的flag字段。原始action的作用域只在switchMap的回调参数里,要把flag传递到后续操作,有两种常用实现方案:

方案1:把tap移入switchMap内部管道(推荐,无需修改现有代码结构)

直接在switchMap内部的API请求管道中添加tap,此时还在原始action的作用域内,可以直接拿到flag值:

updateCustomer$ = createEffect(() =>
  this.actions$.pipe(
    ofType(updateCustomer),
    switchMap(action =>
      this.customerService.updateCustomer(action.customer).pipe(
        map(response => {
          return successLoad({ data: response });
        }),
        tap((newAction) => {
          // 此处可以直接访问外层switchMap的原始action参数
          console.log('原始action的flag值:', action.flag);
          // 执行业务逻辑
        }),
        catchError(EMPTY)
      )
    )
  )
);

方案2:将flag挂载到返回的新Action中传递

如果需要在switchMap外层的多个操作符中使用flag,可以在构造successLoad的时候把flag作为参数传入,需要先修改successLoad的props定义:
首先修改Action定义:

// 给successLoad新增可选的flag字段
export const successLoad = createAction(
  '[API] Load Success',
  props<{ data: any, flag?: string }>()
);

然后修改Effect代码:

updateCustomer$ = createEffect(() =>
  this.actions$.pipe(
    ofType(updateCustomer),
    switchMap(action =>
      this.customerService.updateCustomer(action.customer).pipe(
        map(response => {
          // 返回时把flag也带上
          return successLoad({ data: response, flag: action.flag });
        }),
        catchError(EMPTY)
      )
    ),
    tap((action) => {
      console.log('传递过来的flag值:', action.flag);
      // 执行业务逻辑
    })
  )
);

注意事项

  • 如果你的catchError返回的是EMPTY,报错时后续的tap不会触发,符合正常的异常流程逻辑,无需额外处理。
  • 方案1不需要修改其他代码,适合仅在当前位置使用flag的场景;方案2适合需要在多个下游操作符中使用flag的场景。

内容的提问来源于stack exchange,提问作者Learn AspNet

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 13:06:03