Search code examples
javascriptangularangular-routing

Converting lazy loaded module into an eagerly loaded module


I would like to convert one of my lazy loading modules into eagerly loading module. I have this code in my app-routing.module.ts:

const accountModule = () => import('./account/account.module').then(x => x.AccountModule);
const adminModule = () => import('./admin/admin.module').then(x => x.AdminModule);
const profileModule = () => import('./profile/profile.module').then(x => x.ProfileModule);
const scheduleModule = () => import('./schedule/schedule-routing.module').then(x => x.ScheduleRoutingModule);


const routes: Routes = [
    { path: '', component: HomeComponent, canActivate: [AuthGuard] },
    { path: 'account', loadChildren: accountModule },
    { path: 'profile', loadChildren: profileModule, canActivate: [AuthGuard] },
    { path: 'admin', loadChildren: adminModule, canActivate: [AuthGuard], data: { roles: [Role.Admin] } },
    { path: 'schedule', loadChildren: scheduleModule },
    { path: 'report', component: RaportForDateComponent },
    { path: 'floating', component: FloatingSchedulesComponent },

    // otherwise redirect to home
    { path: '**', redirectTo: '' }
];

I would like to convert account into eagerly loading module. This is my account-routing.module module:

const routes: Routes = [
    {
        path: '', component: LayoutComponent,
        children: [
            { path: 'login', component: LoginComponent },
            { path: 'register', component: RegisterComponent },
            { path: 'verify-email', component: VerifyEmailComponent },
            { path: 'forgot-password', component: ForgotPasswordComponent },
            { path: 'reset-password', component: ResetPasswordComponent }
        ]
    }
];

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

What do I need to change in my app-routing.module.ts Routes for app-routing.module.ts module to be eagerly loaded?


Solution

  • You need to import AccountModule directly in

    app.module.ts

    @NgModule({
      imports: [AccountModule, AppRoutingModule],
      ...
    

    and update root path in AccountRoutingModule.

    account-routing.module.ts

    {
        path: 'account', component: LayoutComponent,
               ^^^^^^^^
        children: [
            { path: 'login', component: LoginComponent },
    

    And finally, of course, don't forget to remove lazy part in

    app-routing.module.ts

    { path: 'account', loadChildren: accountModule },