简体   繁体   中英

Ngrx with lazy load modules

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

  • Login module
  • Admin module

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 :

在此处输入图像描述


Doesn't work after refresh page on the AdminModule the store is empty: 在此处输入图像描述

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM