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 頁面(放在最後)
實作
- 建立
home/about/not-found三個元件 - 寫好上述
routes於AppRoutingModule - 確定
AppModule已 importAppRoutingModule - 到
/、/about、/xyz分別測試三種情況
作業
- 建立首頁、關於、404 三個路由
- 解釋
path: '**'的用途 - 說出
forRoot與exports的作用