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

为何实现NGRX时出现Null Injector错误?

解决Angular 17 + NGRX 出现No provider for StateObservable的问题

问题原因

这个错误通常是Angular 17的独立组件模式与NGRX传统模块导入方式不匹配,或者NGRX版本与Angular 17不兼容导致的。Angular 17默认启用独立组件,传统NgModule导入Store的方式无法为独立组件正确注入依赖。

解决方案

1. 确保NGRX版本与Angular 17兼容

Angular 17必须搭配NGRX 17及以上版本,先检查package.json中@ngrx/store的版本,若低于17.x,执行升级命令:

npm install @ngrx/store@latest

2. 适配Angular 17的独立组件模式

如果你的组件是独立组件(带有standalone: true),推荐使用Angular 17的新提供者API替代传统的StoreModule.forRoot:

方式一:在main.ts中使用provideStore

删除AppModule中StoreModule.forRoot的导入,改为在main.ts的bootstrap配置中注入Store:

// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideStore } from '@ngrx/store';
import { reducers } from './ngrx';
import { AppComponent } from './app/app.component';

bootstrapApplication(AppComponent, {
  providers: [
    provideStore(reducers),
    // 其他需要的提供者
  ]
});

方式二:关联NgModule与独立组件

如果仍想保留NgModule,确保将独立组件添加到AppModule的declarations数组中:

// app.module.ts
@NgModule({
  declarations: [HomeComponent], // 把独立组件加入declarations
  imports: [
    StoreModule.forRoot(reducers, {})
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

3. 修正State类型定义

你的State接口为空,但reducers中已注册heroReducers,补全类型定义以获得正确的类型提示:

// ./ngrx/index.ts
import { ActionReducerMap } from "@ngrx/store";
import { HeroReducers, HeroState } from "../home/hero/hero.reducers";

// 定义完整的根状态类型
export interface State {
  heroReducers: HeroState;
};

export const reducers: ActionReducerMap<State> = {
    heroReducers: HeroReducers
}

然后在组件中使用正确的类型:

constructor(
    private store: Store<State> // 使用定义好的State接口
) {}

验证

修改完成后重启开发服务器,检查错误是否消失。如果仍有问题,确认组件是否为独立组件,以及Store的初始化是否只执行了一次(避免重复导入StoreModule.forRoot)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 06:45:25