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

Ngrx Effect中动作映射出现类型错误,求助解决

解决Ngrx Effect中动作映射的TypeScript错误

错误原因

你的代码里,else分支返回的是Observable<Action>,但外层用了map操作符,导致整个流的类型变成Observable<Action | Observable<Action>>。而Ngrx Effect要求输出必须是Observable<Action>,TypeScript检测到返回的Observable对象缺少Action必需的type属性,因此抛出错误。

修复后的代码

把内层的map替换成switchMap(若无需并行处理请求,switchMap更合适;需并行则用mergeMap),将内部Observable“展平”为Action流:

loadUserUnitScore = createEffect(() =>
    this.actions$.pipe(
      ofType(userActions.loadUserUnitScore),
      mergeMap((scoreParams) =>
        this.databaseService.getUserScoreForEntity(scoreParams).pipe(
          switchMap((userUnitScore) => {
            if ('thematicUnit' in userUnitScore) {
              // 用of包装同步Action,保证分支返回类型一致
              return of(userActions.userUnitScoreLoaded({ userUnitScore }));
            } else {
              return this.structureService
                .getUnit((userUnitScore as DraftUserUnitScore).unitId)
                .pipe(
                  map((unit) =>
                    userActions.userUnitScoreLoaded({
                      userUnitScore: buildUserUnitScoreFromDraft(
                        userUnitScore as DraftUserUnitScore,
                        unit
                      )
                    })
                  )
                );
            }
          })
        )
      )
    )
  );

关键改动说明

  1. 替换内层map为switchMap:switchMap会订阅内部返回的Observable,将其发射的值合并到外层流中,确保整个流输出的都是Action类型,而非Observable<Action>。
  2. 用of()包装同步Action:让if和else分支的返回类型统一为Observable<Action>,符合TypeScript的类型校验规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 05:24:10