从Angular/NgRx 13升级到15后出现Null Injector Error的解决方法
检查NgRx依赖版本一致性
确保所有NgRx相关包(@ngrx/store、@ngrx/effects、@ngrx/entity等)版本统一为15.2.1,与Angular 15.2.2兼容。执行npm list @ngrx/*查看各包版本,若存在不一致,重新安装指定版本:npm install @ngrx/store@15.2.1 @ngrx/effects@15.2.1 @ngrx/entity@15.2.1 @ngrx/router-store@15.2.1确认StoreModule.forRoot的配置正确性
Angular 14+后,NgRx的StoreModule.forRoot无需额外提供StoreRootModule,检查根模块(AppModule)的导入写法:import { StoreModule } from '@ngrx/store'; import { reducers, metaReducers } from './reducers'; @NgModule({ imports: [ // 正确配置方式 StoreModule.forRoot(reducers, { metaReducers }) ] }) export class AppModule { }注意:仅根模块可使用StoreModule.forRoot,功能模块需用
StoreModule.forFeature注册特性reducer,避免重复导入引发冲突。调整模块导入顺序
确保StoreModule.forRoot在所有依赖NgRx的模块(如EffectsModule.forRoot)之前导入,根模块的imports数组中,StoreModule需排在EffectsModule、RouterModule等依赖它的模块前面,保证注入时机正确。清理缓存并重建项目
删除node_modules和锁文件,重新安装依赖后构建项目:# Linux/Mac rm -rf node_modules package-lock.json npm install ng serve # Windows rmdir /s /q node_modules del package-lock.json npm install ng serve排查懒加载模块冲突
检查所有懒加载模块,确认未错误导入StoreModule.forRoot,仅能使用StoreModule.forFeature。同时验证懒加载模块内的NgRx服务是否正确提供,避免重复注入导致的依赖混乱。验证Angular编译器配置
查看tsconfig.json中的compilerOptions,若开启strictNullChecks等严格模式选项,可暂时关闭后测试是否解决问题,部分旧代码可能在严格模式下引发注入异常。
内容的提问来源于stack exchange,提问作者Reza Nikfal

