Search code examples
javascriptangularangular-moduleangular-redux

How can I access angular-redux store from child module?


In my angular app I use angular-redux for application state management. In my main module I defined my redux store. Like this:

export class MainModule {
  constructor(private ngRedux: NgRedux<MainAppState>,
              private devTools: DevToolsExtension) {
    let enhancers = [];

    if (environment.production === false && devTools.isEnabled()) {
      enhancers = [...enhancers, devTools.enhancer()];
    }

    this.ngRedux.configureStore(
      reducer,
      {} as MainAppState,
      [],
      enhancers);
  }
}

I created new child module, which contains some components. These components should access to application state. In one of these components I access via @select to store, but this doesn't work. Here is how I access to store:

export function getLanguage(state: LanguageState) { return state.userLanguage; }

And this code I have in my ChildComponent class:

export class ChildComponent implements OnInit {

  @select(getLanguage) savedUserLanguage$: Observable<LanguageState>;

  // more code

}

How can I access to application state store from child modules? What should I import in child module? Will It be better to create own module only for redux store handling? Maybe I forgot something?

I use Angular v4 and @angular-redux/store v6.


Solution

  • I'd recommend creating a separate module that just contains your store, e.g. StoreModule. You can then import your StoreModule into all your child modules and access your store from there. This is the way they go in the official example app:

    StoreModule: https://github.com/angular-redux/example-app/blob/master/src/app/store/module.ts

    Child Module: https://github.com/angular-redux/example-app/blob/master/src/app/elephants/module.ts

    Component in child module: https://github.com/angular-redux/example-app/blob/master/src/app/elephants/page.ts