獨立路由物件與JS模組化


說明

  1. 可以將路由物件獨立定義,然後放入routes陣列
  2. 也可將該獨立物件JS模組化,然後import進app-routing.module.ts

程式碼範例:


將error頁面改為獨立route物件

1.將app-routing.module.ts內的路由設定變更為如下:

import { Routes, RouterModule, Route } from '@angular/router';
const errorRoute: Route = {
  path: '**',
  redirectTo: "/error",
  pathMatch: "full"
}

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

2.在瀏覽器網址列輸入localhost:4200/不是pageA、pageB、error的任意網址測試轉向效果


將error獨立route物件JS模組化

1.在src/app/建立shared資料夾,在src/app/shared/下建立errorRoute.ts檔案

2.將app-routing.module.ts內的以下程式碼複製到src/app/shared/errorRoute.ts

const errorRoute: Route = {
  path: '**',
  redirectTo: "/error",
  pathMatch: "full"
}

3.在src/app/shared/errorRoute.ts內import Route,並且將const errorRoute export,現在src/app/shared/errorRoute.ts內程式碼如下:

import { Route } from '@angular/router';

export const errorRoute: Route = {
  path: '**',
  redirectTo: "/error",
  pathMatch: "full"
}

4.將app-routing.module.ts內的步驟2程式碼砍掉,現在會routes陣列中的errorRoute會紅字報錯

5.在app-routing.module.ts內import剛才的errorRoute.ts

import { errorRoute } from './shared/errRoute';

6.在瀏覽器網址列輸入localhost:4200/不是pageA、pageB、error的任意網址測試轉向效果

results matching ""

    No results matching ""