为什么实施 NGRX 会因空注入器错误而失败?

问题描述 投票:0回答:1

我已在我的 app.module 中导入了 @ngrx/store,如下所示:

import { StoreModule } from '@ngrx/store';
import { reducers } from './ngrx';

@NgModule({
  declarations: [
  ],
  imports: [
    StoreModule.forRoot(reducers, {})

  ],
  providers: [],
  bootstrap: []
})
export class AppModule {}

当我尝试在组件中使用商店(如下所示)时,出现如下错误:

constructor(
    private store:Store<{heroReducers}>
  ) {}

ERROR Error [NullInjectorError]: R3InjectorError(Standalone[_HomeComponent])[StateObservable -> StateObservable -> StateObservable -> StateObservable]: 

NullInjectorError:没有 StateObservable 的提供者! 在 NullInjector.get (/home/keith/kkw/programming/angular/pizza/client/node_modules/@angular/core/fesm2022/core.mjs:5682:27) 在 R3Injector.get (/home/keith/kkw/programming/angular/pizza/client/node_modules/@angular/core/fesm2022/core.mjs:6125:33) 在 R3Injector.get (/home/keith/kkw/programming/angular/pizza/client/node_modules/@angular/core/fesm2022/core.mjs:6125:33) 在 R3Injector.get (/home/keith/kkw/programming/angular/pizza/client/node_modules/@angular/core/fesm2022/core.mjs:6125:33) 在 R3Injector.get (/home/keith/kkw/programming/angular/pizza/client/node_modules/@angular/core/fesm2022/core.mjs:6125:33) 在 ChainedInjector.get (/home/keith/kkw/programming/angular/pizza/client/node_modules/@angular/core/fesm2022/core.mjs:15424:36) 在lookupTokenUsingModuleInjector(/home/keith/kkw/programming/angular/pizza/client/node_modules/@angular/core/fesm2022/core.mjs:4193:39) 在 getOrCreateInjectable (/home/keith/kkw/programming/angular/pizza/client/node_modules/@angular/core/fesm2022/core.mjs:4241:12) 在 ɵɵdirectiveInject (/home/keith/kkw/programming/angular/pizza/client/node_modules/@angular/core/fesm2022/core.mjs:12042:19) 在Module.ɵɵinject(/home/keith/kkw/programming/angular/pizza/client/node_modules/@angular/core/fesm2022/core.mjs:998:42){ ngTempTokenPath:空, ngTokenPath: [ '状态可观察', '状态可观察', '状态可观察', '状态可观察' ] }

Reducer 在这里注册(./ngrx/index.ts):

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

export interface State {};

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

我在许多应用程序中都以这种方式使用了 NGRX。不知道这个错误是否是由于 Angular 17 与最新的 NGRX 不兼容造成的。

angular ngrx
1个回答
0
投票

请尝试用这种方式导入

...
export class Component1Component implements OnInit {
  demo: Observable<Demo[]>;

  constructor(private store: Store<AppState>) { // <--- changed here!
    this.demo = store.select('heroReducers'); // <--- changed here!
  }
  ...
}

这里是 angular17 上的工作 stackblitz,您可以将其用作参考并确定问题可能发生在哪里。

分叉堆栈闪电战

如果您无法使用此解决方案解决问题,请尝试复制问题并分享该问题的完整可重现代码,并分享 stackblitz!

© www.soinside.com 2019 - 2024. All rights reserved.