Week 04 · Day 06 — 路由守衛(Guard)
學習目標
- 理解
CanActivate守衛的用途 - 用守衛擋下未登入的存取
- 掌握守衛的回傳值與導覽
重點
守衛是什麼
- 在「能否進入某路由」前檢查的邏輯
- 例如:必須登入才能看管理頁
- 回傳 true 放行,false 拒絕(並導向登入頁)
AuthGuard 範例
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(): boolean {
const isLoggedIn = /* check auth, e.g. authService.isAuthenticated() */;
if (isLoggedIn) {
return true;
}
this.router.navigate(['/login']); // 沒登入 → 導向登入頁
return false;
}
}
套用到路由
const routes: Routes = [
{
path: 'admin',
component: AdminComponent,
canActivate: [AuthGuard] // 進入前先檢查
}
];
執行流程
1. 使用者嘗試進入 /admin
2. Angular 呼叫 AuthGuard.canActivate()
3. 已登入 → 回傳 true 放行
4. 未登入 → navigate(['/login']) + 回傳 false 擋下
實作
- 建立
AuthGuard(implementsCanActivate) - 把
canActivate加到某個受保護路由 - 測試登入/未登入兩種情況的導向結果
作業
- 建立一個
CanActivate守衛 - 將守衛套用到受保護路由
- 說明回傳
false時會發生什麼