函数式路由守卫
使用函数式守卫保护路由
函数式路由守卫 是 CoddyKit 上的免费 Angular Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Angular Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Angular Academy 课程共包含 4 节课。
什么是路由守卫
守卫决定是否可以继续导航:保护需要身份验证的路由、在离开表单前进行确认,或根据角色限制访问。现代 Angular 使用函数式守卫——普通函数,而不是类。
CanActivateFn
CanActivateFn 返回 true 表示允许,返回 false 表示阻止,返回 UrlTree 表示重定向,也可以返回这些值对应的可观察对象或 Promise。
import { CanActivateFn } from '@angular/router';
import { inject } from '@angular/core';
export const authGuard: CanActivateFn = () => {
const auth = inject(AuthService);
return auth.isLoggedIn();
};将守卫连接到路由
使用 canActivate 添加守卫(它是一个数组,因此您可以叠加多个守卫)。
export const routes = [
{ path: 'dashboard', component: DashboardComponent,
canActivate: [authGuard] }
];使用 UrlTree 重定向
返回一个 UrlTree(来自 router.createUrlTree 或 parseUrl)即可在一个步骤中同时阻止并重定向。
export const authGuard: CanActivateFn = () => {
const auth = inject(AuthService);
const router = inject(Router);
return auth.isLoggedIn() ? true : router.parseUrl('/login');
};异步守卫
守卫可以返回可观察对象——路由器会等待第一个值,然后完成订阅。
export const authGuard: CanActivateFn = () => {
const auth = inject(AuthService);
return auth.checkSession$().pipe(
map(ok => ok ? true : inject(Router).parseUrl('/login'))
);
};在守卫中访问路由信息
CanActivateFn 会接收 ActivatedRouteSnapshot 和 RouterStateSnapshot,因此您可以读取参数、数据以及尝试访问的 URL。
export const roleGuard: CanActivateFn = (route, state) => {
const needed = route.data['role'];
const auth = inject(AuthService);
return auth.hasRole(needed);
};canMatch 守卫
CanMatchFn 决定路由定义是否完全匹配——这对于根据功能标志切换路由,或仅在获得许可时进行延迟加载非常有用。
import { CanMatchFn } from '@angular/router';
export const featureGuard: CanMatchFn = () =>
inject(FeatureService).enabled('beta');canDeactivate 守卫
CanDeactivateFn 会在离开路由时运行,非常适合用于确认未保存的更改。它会接收组件实例。
import { CanDeactivateFn } from '@angular/router';
export const unsavedGuard: CanDeactivateFn<FormComponent> =
(component) => component.isPristine() || confirm('Discard changes?');叠加多个守卫
数组中的所有守卫都必须允许导航。它们会一起运行;如果任何守卫返回 false 或 UrlTree,导航就会被阻止或重定向。
canActivate: [authGuard, roleGuard]
// both must pass为什么选择函数式守卫而非类守卫
函数式守卫更简单:无需 @Injectable 样板代码,可以轻松使用 inject(),支持组合,并且可进行树摇优化。基于类的 CanActivate 接口已弃用。
守卫与子路由
canActivateChild 可以在一个位置保护父路由的所有子路由,避免在每个子路由上重复配置守卫。
{ path: 'admin', canActivateChild: [authGuard],
children: [ /* all protected */ ] }快速检查
测试您对函数式守卫的理解。
回顾:函数式路由守卫
函数式守卫使用普通函数控制导航。
CanActivateFn:允许、阻止或重定向(UrlTree)。CanMatchFn:决定路由是否匹配。CanDeactivateFn:确认是否离开。- 使用
inject()获取服务,并在数组中叠加守卫。
下一步:路由器事件和导航。
常见问题解答
「函数式路由守卫」课时是免费的吗?
是的 — 「函数式路由守卫」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Angular Academy 课程的其余内容,请升级到 CoddyKit PRO。 Angular Academy 课程共包含 4 节课。
「函数式路由守卫」这节课中我会学到什么?
使用函数式守卫保护路由 你通过在浏览器中直接运行的动手代码来练习 Angular Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Angular Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Angular Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「函数式路由守卫」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Angular Academy 课中编写并运行代码吗?
能。每节 Angular Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。