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

在NGRX Effect中返回多组Action时遇TypeScript错误

解决NgRx Effect中根据布尔值返回不同Action组的问题

看起来你想在Effect里根据API返回结果的某个布尔值,触发两组不同的Action序列对吧?我来帮你调整代码,同时纠正一个可能隐藏的问题——你获取路由参数的方式不太对,因为this.routerStore.select(fromRouter.getCompanyId)返回的是Observable,直接用obs2Str大概率拿不到正确的ID值,应该用withLatestFrom来获取最新的参数值。

下面是修正后的完整代码:

@Effect()
loadCompanyDetail = this.actions$.pipe(
  ofType(fromActions.COMPANY_DETAIL_LOAD),
  // 用withLatestFrom获取最新的companyId值
  withLatestFrom(this.routerStore.select(fromRouter.getCompanyId)),
  switchMap(([action, companyId]) => {
    // 确保companyId是可用的字符串类型,可根据实际情况调整处理逻辑
    const targetId = typeof companyId === 'string' ? companyId : fromUtility.obs2Str(companyId);
    return this.companyService.getCompanyByID(targetId).pipe(
      map(res => {
        // 根据res中的布尔属性判断返回哪组Action
        if (res.isValid) { // 替换成你实际的布尔判断条件
          // 返回第一组Action数组,NgRx会按顺序分发
          return [
            new fromActions.CompanyDetailLoadSuccess(res),
            new fromActions.TriggerFirstGroupAction1(),
            new fromActions.TriggerFirstGroupAction2()
          ];
        } else {
          // 返回第二组Action数组
          return [
            new fromActions.CompanyDetailLoadSuccess(res),
            new fromActions.TriggerSecondGroupActionA(),
            new fromActions.TriggerSecondGroupActionB()
          ];
        }
      }),
      catchError(error => {
        // 处理API请求错误,返回失败Action
        return of(new fromActions.CompanyDetailLoadFail(error));
      })
    );
  })
);

关键说明:

  • 正确获取路由参数:用withLatestFrom订阅路由参数的Observable,能拿到当前最新的companyId值,避免直接处理Observable对象导致的错误。
  • 按条件返回Action组:在map操作符里根据布尔判断返回不同的Action数组,NgRx会自动按数组顺序依次分发这些Action。
  • 错误处理:必须添加catchError,防止Effect因API请求失败而被终止,保证后续Effect能正常运行。

如果你的返回结果res里有特定的布尔判断字段,只需要把res.isValid替换成实际的属性名即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:03:05