I am working on an Angular application that has lazy loading implemented. I tried experimenting with lazy loading but decided that I do not yet want to implement it in my ap
I like doing it by changing string to arrow function looking something like:
import { HqModule } from './hq/hq.module';
{ path: 'hq', loadChildren: () => HqModule },
for aot angular 4 and less:
export function loadHqModuleFn() {
return HqModule;
}
{ path: 'hq', loadChildren: loadHqModuleFn },
Note: Beginning in version 5, the compiler automatically performs this rewritting while emitting the .js file. Thanks to "expression lowering"
Plunker Example
If you use angular-router-loader then you should be aware that this loaded has special syntax for to load module synchronously. Just add the sync=true
as a query string value to your loadChildren string
:
{ path: 'hq', loadChildren: 'app/hq/hq.module#HqModule?sync=true' },
Of course you can just add module to imports
array but in this case you have to change router config path for this module:
app.module.ts
@NgModule({
imports: [
...,
HqModule,
BrowserModule,
RouterModule.forRoot([
{ path: '', redirectTo: 'store', pathMatch: 'full'},
{ path: 'store', loadChildren: 'app/store/store.module#StoreModule', pathMatch: 'prefix'},
])
]
...
})
export class AppModule {}
hq.module.ts
@NgModule({
imports: [
...
RouterModule.forChild([
{ path: 'hq', <========================== changed '' to `hq`
component: HqTemplateComponent,
canActivate: [AuthGuard],
children: [
...
]
},
]),
],
...
})
It's also worth mentioning that angular router config is strict about order. According to the docs:
The router uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes
So add modules with routes definition to imports
array in the same order as if you would do it in RouterModule.forRoot
.
Add HqModule
to your AppModule's import array and remove HqModule entry from the AppModule routing definition. Like this:
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
HqModule, // add it
RouterModule.forRoot([
{ path: '', redirectTo: 'store', pathMatch: 'full'},
{ path: 'store', loadChildren: 'app/store/store.module#StoreModule', pathMatch: 'prefix'}
])
],
bootstrap: [AppComponent],
exports: [RouterModule],
})
export class AppModule { }