Lazy Loading
如題,需要的時候才載入某個 module
在 Routing 這個篇章用到的範例,總共有三個 Module
要如何將 BlogsModule 設定成 Lazy Loading 呢?
首先要調整 app.module.ts
const appRoutes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'users', component: ChatListComponent, outlet: 'chat', canActivate: [AuthGuardService]},
{ path: 'users/:username', component: ChatComponent, outlet: 'chat', canActivate: [AuthGuardService]},,
{ path: 'blogs', loadChildren: 'app/blogs/blogs.module#BlogsModule' },
{ path: '', redirectTo: '/forums', pathMatch: 'full'},
{ path: '**', component: NotFoundComponent }
];
因為目前沒有 BlogsModule,所以我們來建立一個,並填入以下內容:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BlogsComponent } from './blogs/blogs.component';
import { BlogComponent } from './blog/blog.component';
import { BlogsService } from './services/blogs.service';
import { BlogsRoutingModule } from './blogs-routing.module';
@NgModule({
imports: [
CommonModule,
BlogsRoutingModule
],
declarations: [
BlogsComponent,
BlogComponent,
],
providers: [
BlogsService
]
})
export class BlogsModule { }
```
- 這邊只有一個重點,就是 BlogsRoutingModule
- 所以接著還要補上 BlogsRoutingModule:
```typescript=
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { BlogsComponent } from './blogs/blogs.component';
import { BlogComponent } from './blog/blog.component';
const routes: Routes = [
{ path: '', component: BlogsComponent },
{ path: ':post_id', component: BlogComponent }
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
providers: []
})
export class BlogsRoutingModule { }
```
- 這裡宣告了 **routes** 陣列,空字串的 path 與 **:post_id** 對到了各句的 Component
- 比較特別的是,這裡的 路徑都是相對的,因為前面的部份已經在 AppModule 裡定義好了
- 另外就是這裡的 imports 是用 RouterModule.**forChild**,只要不是在 AppModule 裡,基本上都是 forChild
- 最後最後,還要 export RouterModule,這樣這個 **BlogsModule** 底下的 component 才能使用 routing 相關的 directive
- 最後我們再回到 app.component.html
```html=
<a class="nav-link"
routerLink="/blogs">
<span class="nav-text">Blogs</span>
</a>
```
- 其實是個單純的 routerLink
- 但因為是 lazy load,所以點在 link 上的時候會再非同步發一個 request,如下圖:

When you subscribe to the blog, we will send you an e-mail when there are new updates on the site so you wouldn't miss them.
評論