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

Ngrx Effect中使用MergeMap出现类型错误如何解决

NgRX Effect mergeMap 类型错误解决方案

错误原因

  • 多余的any类型声明覆盖了NgRX内置的类型推断,导致类型校验不通过
  • catchError返回的EMPTY流默认没有匹配NgRX Effect要求的Action返回类型,触发类型冲突
  • 可选优化点:Action的props声明为any类型不符合类型安全要求,也可能引发隐式类型冲突

修复步骤

1. 修正Action的props类型

将retreivedCategories的props从any替换为和接口返回一致的SocialLearningCategory[]类型:

import { createAction, props } from '@ngrx/store';
import type { SocialLearningCategory } from '../../../../core/models/socialLearningCategory';

export const loadCategories = createAction('load categories');

export const retreivedCategories = createAction(
  'retreived social learning categories',
  props<{ socialLearningCategories: SocialLearningCategory[] }>()
);

2. 修正Effect代码

移除所有多余的any类型声明,给EMPTY添加类型断言匹配Action类型,同时可修正复制示例残留的错误命名:

import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { Action } from '@ngrx/store';
import { EMPTY, Observable } from 'rxjs';
import { map, mergeMap, catchError } from 'rxjs/operators';
import { SocialLearningFacadeService } from '../../facades/social-learning-facade.service';
import { loadCategories, retreivedCategories } from '../actions/categories';

@Injectable()
export class CategoriesEffects {
  // 移除any声明,允许TS自动推断类型,也可手动标注为 Observable<Action>
  loadCategories$ = createEffect((): Observable<Action> =>
    this.actions$.pipe(
      ofType(loadCategories),
      mergeMap(() =>
        this.socialLearningFacadeService.getSocialLearningCategories().pipe(
          map((categories) =>
            retreivedCategories({ socialLearningCategories: categories })
          ),
          // 给EMPTY添加类型断言,匹配Effect要求的返回类型
          catchError(() => EMPTY as Observable<Action>)
        )
      )
    )
  );

  constructor(
    private actions$: Actions,
    private socialLearningFacadeService: SocialLearningFacadeService
  ) {}
}

3. 版本校验(可选)

如果修改后仍有类型错误,检查当前NgRX版本是否和项目Angular主版本匹配,大版本不一致会引发内置类型不兼容问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:57:05