延迟加载示例
延迟加载模块可以帮助我们缩短启动时间。使用延迟加载,我们的应用程序不需要一次加载所有内容,它只需要加载用户在应用程序首次加载时期望看到的内容。只有当用户导航到他们的路线时,才会加载延迟加载的模块。
应用程序/ app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { EagerComponent } from './eager.component';
import { routing } from './app.routing';
@NgModule({
imports: [
BrowserModule,
routing
],
declarations: [
AppComponent,
EagerComponent
],
bootstrap: [AppComponent]
})
export class AppModule {}
应用程序/ app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `<h1>My App</h1> <nav>
<a routerLink="eager">Eager</a>
<a routerLink="lazy">Lazy</a>
</nav>
<router-outlet></router-outlet>
`
})
export class AppComponent {}
应用程序/ app.routing.ts
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { EagerComponent } from './eager.component';
const routes: Routes = [
{ path: '', redirectTo: 'eager', pathMatch: 'full' },
{ path: 'eager', component: EagerComponent },
{ path: 'lazy', loadChildren: './lazy.module' }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(routes);
应用程序/ eager.component.ts
import { Component } from '@angular/core';
@Component({
template: '`<p>Eager Component</p>`'
})
export class EagerComponent {}
LazyModule 没有什么特别之处,除了它有自己的路由和一个名为 LazyComponent 的组件(但没有必要为你的模块命名或 simliar)。
应用程序/ lazy.module.ts
import { NgModule } from '@angular/core';
import { LazyComponent } from './lazy.component';
import { routing } from './lazy.routing';
@NgModule({
imports: [routing],
declarations: [LazyComponent]
})
export class LazyModule {}
应用程序/ lazy.routing.ts
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LazyComponent } from './lazy.component';
const routes: Routes = [
{ path: '', component: LazyComponent }
];
export const routing: ModuleWithProviders = RouterModule.forChild(routes);
应用程序/ lazy.component.ts
import { Component } from '@angular/core';
@Component({
template: `<p>Lazy Component</p>`
})
export class LazyComponent {}