Week 04 · Day 03 — 基礎路由設定

學習目標

  • 定義 Routes 陣列
  • 學會 path 對應元件的寫法
  • 設定 404 頁面

重點

規則 - 路由告訴 Angular:當 URL 是某路徑時,顯示哪個元件 - 用 Routes 陣列定義,交給 RouterModule.forRoot(routes)

基本路由設定

import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { NotFoundComponent } from './not-found/not-found.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: '**', component: NotFoundComponent }  // 萬用(404)
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]   // 讓其他檔案能用 routerLink 等
})
export class AppRoutingModule { }

path 說明 - '':根路徑(首頁) - 'about'/about - '**':任何沒匹配到的路徑 → 404 頁面(放在最後)

實作

  1. 建立 home / about / not-found 三個元件
  2. 寫好上述 routesAppRoutingModule
  3. 確定 AppModule 已 import AppRoutingModule
  4. //about/xyz 分別測試三種情況

作業

  • 建立首頁、關於、404 三個路由
  • 解釋 path: '**' 的用途
  • 說出 forRootexports 的作用