範例# 子路由模組化與延遲載入

說明

  1. 將子路由中所含元件模組化
  2. 該模組可以含有本身模組的路由
  3. 透過延遲載入,可以在需要進入該模組路由時才載入模組,不用預先載入

程式語法:

上層模組路由設定

const routes: Routes = [
  {
    path: 'child',
    loadChildren: '下層模組ts檔路徑#下層模組名稱'
  }
];

下層模組路由設定

const routes: Routes = [
  { path: '', redirectTo: 'child1', pathMatch: 'full'},
  { path: 'child1', component: child1Component},
  { path: 'child2', component: child2Component},

];

網址如下

localhost:4200/child/child1

程式碼範例:

1.建立含路由的模組child

ng g m child --routing

2.將c1元件與c2元件放入child模組,child.module.ts內程式如下:

@NgModule({
  imports: [
    CommonModule,
    ChildRoutingModule
  ],
  declarations: [
    C1Component,
    C2Component
  ]
})

2.從app.module.ts中將c1與c2的宣告移除

@NgModule({
  declarations: [
    AppComponent,
    PageAComponent,
    PageBComponent,
    ErrorComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRoutingModule
  ],
  providers: [TestService],
  bootstrap: [AppComponent]
})

並移除import

import { C2Component } from './c2/c2.component';
import { C1Component } from './c1/c1.component';

3.從app-routing.module.ts中將c1與c2的路由移除

const routes: Routes = [
  {
    path: '',
    redirectTo: "/pageA",
    pathMatch: "full"
  },
  {
    path: 'pageA',
    component: PageAComponent
  },
  {
    path: 'pageB',
    component: PageBComponent
  },
  {
    path: 'error',
    component: ErrorComponent
  },
  errorRoute
];

並移除下面兩行import

import { C2Component } from './c2/c2.component';
import { C1Component } from './c1/c1.component';

3.在child-routing.module.ts中設定路由

const routes: Routes = [
  {path: '', redirectTo: 'c1', pathMatch: 'full'},
  {path: 'c1', component: C1Component},
  {path: 'c2', component: C2Component}
];

5.在app-routing.module.ts中設定延遲載入child模組

const routes: Routes = [
  {
    path: '',
    redirectTo: "/pageA",
    pathMatch: "full"
  },
  {
    path: 'pageA',
    component: PageAComponent
  },
  {
    path: 'pageB',
    component: PageBComponent
  },
  {
    path: 'child',
    loadChildren: './child/child.module#ChildModule'
  },
  {
    path: 'error',
    component: ErrorComponent
  },
  errorRoute
];

6.瀏覽器輸入http://localhost:4200/child測試

7.在app.component.html中修改c1和c2的超連結

<li><a [routerLink]="['/child', 'c1']" routerLinkActive="activeStyle" [routerLinkActiveOptions]="{exact: true}">來去page-c1</a></li>
        <li><a routerLink="/child/c2" routerLinkActive="activeStyle" [routerLinkActiveOptions]="{exact: true}">來去page-c2</a></li>

8.測試來去page-c1來去page-c2兩個超連結

results matching ""

    No results matching ""