How to define lazy Module paths in angular2 and lo

2019-08-12 05:56发布

问题:

I have different components and routes based on roles. Now i have defined routes as for certain components as below

Login Module 
path: '', loadChildren:'app/login/login.module#LoginModule';

Register Module 
path:'', loadChildren: 'app/register/register.module#LoginModule'

Dashboard Module
path:'' loadChildren:'app/dashboard/dashboard.module#dashboardModule'

User Profile Module
path:'' loadChildren:'app/user-profile/user-profile.module#UserProfileModule'

Now whenever I navigate to login or register page all the listed module chunks are getting loaded all together and page is slightly delayed and stucks until module chunks are not loading. Does anyone has idea how to define path and stop the unwanted module load on specific path. Thanks in advance for any help

回答1:

You will need to specify a route under your module will be executed.

Note that all lazy-loaded module must follow these three rules.

  1. The module which you want to lazy load they should have one parent route.
  2. Dont import module in your app.module.ts. Because if you do then no point of lazy loading
  3. Your will need to configure under one route in your app.routes.

So to answer your question you will need config like this..

{
// Login Module 
path: 'login', loadChildren:'app/login/login.module#LoginModule';

// Register Module ,
path:'register', loadChildren: 'app/register/register.module#LoginModule'

// Dashboard Module
path:'dashboard', loadChildren:'app/dashboard/dashboard.module#dashboardModule'

// User Profile Module
path:'profile', loadChildren:'app/user-profile/user-profile.module#UserProfileModule'

}

So whenever you will hit login route it will load the #LoginModule. In your login module should export routes like this

const routes: Routes = [
    { 
        path: '', 
        children: [
           {
           path: '',
           component: YourComponentToLoad 
           }
        ]
    }
]

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})

export class LoginRoutingModule {

}

Also, in your app-routing.module.ts you can define preloading strategy as following so that after the app is initialized, lazy modules will start loading immediately. So, when user clicks on a link and wants to see a lazy loaded module, it'll be ready.

app-routing.module.ts

@NgModule({
    imports: [RouterModule.forRoot(routes, {preloadingStrategy: PreloadAllModules})],
    exports: [RouterModule]
})
export class AppRoutingModule {