Search code examples
angularngrxngrx-store

Using NGRX within Angular Library


I am using NGRX within my application. But within my Angular Library I want to join that NGRX module and add to it. However, when I try to call StoreModule.forRoot() within the library, I can't. Because I already called it once in the main application.

  imports: [
    CommonModule,
    IonicModule,
    CompoLoginRoutingModule,
    ReactiveFormsModule,
    TranslateModule.forRoot({
      loader: {
        deps: [HttpClient],
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
      },
    }),
    StoreModule.forRoot(reducers, { // This is a problem
      runtimeChecks: {
        strictStateImmutability: true,
        strictActionImmutability: true,
      },
      metaReducers,
    }),

Is there a right way to join the NGRX of the main application?


Solution

  • if you are using ngrx store module in app module then please add this section in app.moudle.ts

    import { reducers, metaReducers } from "./reducers";
    
    StoreModule.forRoot(reducers, {
          metaReducers,
          runtimeChecks: {
            strictStateImmutability: true,
            strictActionImmutability: true,
          },
        }),
    

    this is the command for generating root store

    ng generate store AppState --root --module app.module.ts
    

    effects also like this in app.module.ts

    EffectsModule.forRoot([AppEffects]),
    

    if ngrx store module in child module the add like this assets.moudle.ts,

    import * as fromAssetsStore from "./store/assets.reducer";
    
    StoreModule.forFeature(
      fromAssetsStore.assetsFeatureKey,
      fromAssetsStore.aReducer,
      {
        metaReducers: fromAssetsStore.metaReducers,
      }
    ),
    EffectsModule.forFeature([AssetsEffects]),