网站搜索

angular - 有没有办法使用 provideState() 提供多个 reducer 作为根 reducer


当前版本的 Angular 和 ngrx 是 16.0.0。

StoreModule.forRoot({
      app: appReducer,
      anotherFeatureName: anotherFeatureReducer
    }),
    EffectsModule.forRoot([
      AppEffects,
      AnotherEffects
    ]),

我开始迁移到独立的 Angular 应用。因此我需要从 app.module.ts 中移除 StoreModule 和 EffectsModule。但我找不到使用独立 API 提供多个 reducers 和相关 effects 的方法。

尝试了不同的提供方式,但没有一种按预期工作。当应用尝试读取它时,状态是未定义的。

答案#1

1. 首先,确保你已经导入了必要的 NgRx 模块以及你的 reducers 和 effects。

import { provideState } from '@ngrx/store';
import { provideEffects } from '@ngrx/effects';
import { appReducer } from './app.reducer';
import { anotherFeatureReducer } from './another-feature.reducer';
import { AppEffects } from './app.effects';
import { AnotherEffects } from './another.effects';

2. 在你的应用模块中,使用 provideState() 函数来提供你的根 reducers

import { provideState } from '@ngrx/store';

@NgModule({
  imports: [
    //Remove StoreModule.forRoot()
    //Remove EffectsModule.forRoot()
    // Add provideState() to provide your root reducers
    provideState({
      app: appReducer,
      anotherFeatureName: anotherFeatureReducer,
    }),
  ],
})
export class AppModule {}

3. 类似地,使用 provideEffects() 函数来提供你的根效果

import { provideEffects } from '@ngrx/effects';

@NgModule({
  imports: [
    //Remove StoreModule.forRoot()
    //Remove EffectsModule.forRoot()
    // Add provideState() to provide your root reducers
    provideState({
      app: appReducer,
      anotherFeatureName: anotherFeatureReducer,
    }),

    // Add provideEffects() to provide your root effects
    provideEffects([AppEffects, AnotherEffects]),
  ],
})
export class AppModule {}