CoYoTe
CoYoTe

Reputation: 95

Using @ngrx/store into angular 2 module

I'm using @ngrx/store (also @ngrx/effects and @ngrx/store-devtools) in current application successfully. Now I want to make module, that will be ideal to be independent from rest of the application. Problem is how to also use @ngrx/store in it? Can I somehow just add new reducer into existing "app" store? I want to avoid to move model from module to app and make reducer registration into app. Do anyone have solution from this? Example code is below:

// App declarations
export const APP_IMPORTS = [
  .
  .
  .
  StoreModule.provideStore(reducer),
  EffectsModule.run(someEffects),
  STORE_DEV_TOOLS_IMPORTS
];

@NgModule({
  declarations: [
    APP_DECLARATIONS,
    AppComponent
  ],
  imports: [
    APP_IMPORTS
  ],
  providers: [APP_PROVIDERS],
  bootstrap: [AppComponent]
})
export class AppModule {
}

And in new module:

// Module declaration
@NgModule({
  imports: [CommonModule, 
           FormsModule, 
           StoreModule.provideStore({ counter: counterReducer }) // <-- how to change this to just add to current store new reducer??
  ],
  exports: [MyTestComponent],
  declarations: [MyTestComponent],
})
export class SomeModule {
}

Also dose anyone know how to chnage name of @ngrx/store showing on devtool? Change it form ngrx-store-some_random_number to some app_name?

Many thanks

Upvotes: 3

Views: 628

Answers (1)

Felix
Felix

Reputation: 4595

As of ngrx4 you provide store as: StoreModule.forRoot({router: routerReducer})

@NgModule({
    imports: [
        StoreModule.forRoot({router: routerReducer}),
        EffectsModule.forRoot([...]),
        ...
    ],
    declarations: [],
    ...
})
export class AppModule {}

Then in your feature module, you can provide store as StoreModule.forFeature(...):

@NgModule({
    imports: [
        StoreModule.forFeature('feature', featureReducer),
        EffectsModule.forFeature([...]),
        ...
    ],
    declarations: [],
    ...
})
export class FeatureModule {}

The feature state will be then under state.feature key in store.

Use can use selectors to access feature store consistently:

export const selectFeatureModule = createFeatureSelector<FeatureState>('feature');
export const selectFeatureValue = createSelector(selectFeatureModule ,
(state: FeatureState) => state.someValue);

In feature module: an Angular component can use /slice the state as:

...
constructor(private store: Store<AppState>,) {
    this.store.select(selectFeatureValue)
        .subscribe(console.log.bind(console));

}
...

Upvotes: 2

Related Questions