user12251399
user12251399

Reputation:

Ngrx with lazy load modules

Let assume in my application I have the following lazy loading modules:

App-routing.module.ts `

const routes: Routes = [
  { path: 'login', loadChildren: () => import('./login/login.module').then(m => m.LoginModule) },
  { path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule), canLoad: [AdminGuard]}]

`

In the LoginModule I've created StoreModule.forFeature('login', fromLogin.authReducer).

After successful login program redirects to the Admin page(Module).

And the store dispatching new action:this.store.dispatch(login({some object})); Everything works fine.


Problem

When I try to refresh page on the admin module I will lost store from LoginModule.

As you can see in the routing module I'm using Guard canLoad logic inside guard should change state in the LoginModule store but after refresh page I lost it.


Works fine and change state in the LoginModule:

enter image description here


Doesn't work after refresh page on the AdminModule the store is empty: enter image description here

Upvotes: 0

Views: 1301

Answers (1)

GuyTuval
GuyTuval

Reputation: 46

A possible solution would be to place your store management code in the shared module, as it is shared amongst all the lazy loaded feature modules (if you never used a shared module, you can look at this link for reference). Note that you'll need to import the shared module in the app module.

If you are starting now a new project, I will advise you to check out NGXS which is an alternative to NgRX. I have encountered many programmers who decided to migrate their code from NgRX to NGXS, as it eases the complexity of state management.

Upvotes: 1

Related Questions