路由(Routing)基礎
路由基本概念
路由的作用:當使用者瀏覽網站的不同頁面時,Angular 路由負責更新 UI 和瀏覽器網址,讓使用者可以連結到網站的不同部分。
客戶端路由特點:
Angular 會監視並操作 URL
針對不同的 URL 渲染不同的元件
所有路由操作都在瀏覽器中進行,不涉及伺服器端路由
Angular 負責更新 URL、讀取 URL 以及依據當前 URL 載入不同元件
路由配置方法
方法一:直接在 main.ts 中配置
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { AppComponent } from './app/app.component';
import { TasksComponent } from './app/tasks/tasks.component';
bootstrapApplication(AppComponent, {
providers: [
provideRouter([
{
path: 'tasks', // <your-domain>/tasks
component: TasksComponent
}
])
]
}).catch((err) => console.error(err));
方法二:使用獨立的路由檔案
main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { AppComponent } from './app/app.component';
import { routes } from './app/app.routes';
bootstrapApplication(AppComponent, {
providers: [provideRouter(routes)],
}).catch((err) => console.error(err));
app.routes.ts
import { Routes } from '@angular/router';
import { TaskComponent } from './tasks/task/task.component';
export const routes: Routes = [
{
path: 'tasks', // <your-domain>/tasks
component: TaskComponent,
},
];
方法三:使用獨立配置檔案(更精簡)
main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';
bootstrapApplication(AppComponent, appConfig).catch((err) =>
console.error(err)
);
app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes)],
};
路由使用方法
在模板中使用路由
添加 <router-outlet>
元素來顯示當前路由對應的元件:
<nav>
<a routerLink="/">首頁</a>
<a routerLink="/tasks">任務列表</a>
</nav>
<!-- 路由對應的元件將在這裡顯示 -->
<router-outlet></router-outlet>
路由連結
使用 routerLink
指令創建導航連結:
<!-- 基本連結 -->
<a routerLink="/tasks">任務列表</a>
<!-- 帶有類別的連結(當路由激活時應用樣式) -->
<a routerLink="/tasks" routerLinkActive="active-link">任務列表</a>
<!-- 程式化路由參數 -->
<a [routerLink]="['/tasks', task.id]">查看任務</a>
程式化導航
在元件中使用 Router 服務進行導航:
import { Router } from '@angular/router';
export class MyComponent {
constructor(private router: Router) {}
navigateToTasks() {
this.router.navigate(['/tasks']);
}
navigateToTask(id: string) {
this.router.navigate(['/tasks', id]);
}
}
進階路由功能
路由參數
定義帶參數的路由:
const routes: Routes = [
{
path: 'tasks/:id',
component: TaskDetailComponent
}
];
在元件中獲取參數:
import { ActivatedRoute } from '@angular/router';
export class TaskDetailComponent implements OnInit {
taskId: string = '';
constructor(private route: ActivatedRoute) {}
ngOnInit() {
// 快照方式(只獲取一次)
this.taskId = this.route.snapshot.paramMap.get('id') || '';
// 響應式方式(會在參數變化時更新)
this.route.paramMap.subscribe(params => {
this.taskId = params.get('id') || '';
});
}
}
巢狀路由(子路由)
定義巢狀路由結構:
const routes: Routes = [
{
path: 'tasks',
component: TasksComponent,
children: [
{ path: '', component: TaskListComponent },
{ path: ':id', component: TaskDetailComponent }
]
}
];
在父元件中加入子路由出口:
<div class="tasks-container">
<h2>任務管理</h2>
<!-- 子路由元件將在這裡顯示 -->
<router-outlet></router-outlet>
</div>
路由守衛
使用路由守衛保護路由:
import { CanActivateFn } from '@angular/router';
export const authGuard: CanActivateFn = (route, state) => {
// 檢查使用者是否已登入
const isLoggedIn = localStorage.getItem('token') !== null;
if (!isLoggedIn) {
// 未登入時重定向到登入頁面
const router = inject(Router);
router.navigate(['/login']);
return false;
}
return true;
};
在路由配置中使用守衛:
const routes: Routes = [
{
path: 'tasks',
component: TasksComponent,
canActivate: [authGuard]
}
];
其他實用路由功能
路由解析器(Resolver):預先載入資料,避免元件顯示前的延遲
延遲載入模組:提升應用程式啟動速度
路由事件監聽:追蹤路由狀態變化
查詢參數:處理額外的 URL 參數
路由策略:控制 URL 格式和行為
這樣我們就正式啟用並了解如何使用 Angular 的路由功能了!
Last updated