Platform: Best practice for accessing root store from feature module

Created on 16 Mar 2019  路  2Comments  路  Source: ngrx/platform

Hey,

I am facing a "design" problem at the moment - what is best practice to access the root store inside of feature module that has its own store?

My root store (index.ts) is defined like this:

export interface State {
    router: fromRouter.RouterReducerState<RouterStateUrl>;
}

export const reducer: ActionReducerMap<State> = {
    router: fromRouter.routerReducer
};

export const getRouterState = createFeatureSelector<
    fromRouter.RouterReducerState<RouterStateUrl>
>('router');

Then I have a feature store:

export interface MenuState{
    items: MenuItem[];
}

export const initialState: MenuState = {
    items: [ ]
};

The related menu.component.ts needs the current URL from the router-store.
At the moment I have solved the problem like this:

constructor(public store$: Store<fromMenuStore.MenuState>,
    public rootStore$: Store<fromRoot.State>) { }

public ngOnInit(): void {
    this.items = this.store$.pipe(select(fromMenuStore.getMenuItems));
    this.rootStore$.pipe(select(fromRoot.getCurrentUrl)).subscribe(
      url => {
        this.hideMainApp = this.shouldHideMainApp(url);
      }
    )
  }

Is it okay to inject the feature and the root store in this place or is there a better way like extending the root state or something?
It is working I am just not really happy with it...

PS: I could not find any related issue/doc for my problem.

Most helpful comment

There is only one store, injecting stores as shown in the snippet will result in the same store getting injected twice.

constructor(public store$: Store<fromMenuStore.MenuState>,
    public rootStore$: Store<fromRoot.State>) { }

You can indeed extend your feature state with the root state as shown in our example app.

For some more info you can take a look at Sharing data between modules is peanuts.

All 2 comments

There is only one store, injecting stores as shown in the snippet will result in the same store getting injected twice.

constructor(public store$: Store<fromMenuStore.MenuState>,
    public rootStore$: Store<fromRoot.State>) { }

You can indeed extend your feature state with the root state as shown in our example app.

For some more info you can take a look at Sharing data between modules is peanuts.

angularindepth.com seems to be down. I assume https://dev.to/angular/sharing-data-between-modules-is-peanuts-3p36 is the same post.

Was this page helpful?
0 / 5 - 0 ratings