千家信息网

分析Angular路由守卫Route Guards

发表于:2025-11-17 作者:千家信息网编辑
千家信息网最后更新 2025年11月17日,这篇文章主要介绍"分析Angular路由守卫Route Guards",在日常操作中,相信很多人在分析Angular路由守卫Route Guards问题上存在疑惑,小编查阅了各式资料,整理出简单好用的
千家信息网最后更新 2025年11月17日分析Angular路由守卫Route Guards

这篇文章主要介绍"分析Angular路由守卫Route Guards",在日常操作中,相信很多人在分析Angular路由守卫Route Guards问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"分析Angular路由守卫Route Guards"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

环境:

  • Angular CLI: 11.0.6

  • Angular: 11.0.7

  • Node: 12.18.3

  • npm : 6.14.6

  • IDE: Visual Studio Code

在我们的实际的业务开发过程中,我们经常会遇到如下需求:

  • 需要限制某些 URL 的可访问性,例如,对于系统管理界面,只有那些拥有管理员权限的用户才能打开。

  • 当用户处于编辑界面时,在没有保存就离开时,需要提示用户是否放弃修改。

针对以上场景,Angualr使用路由守卫(Route Guards)来实现。

路由守卫(Route Guards)

1. 创建路由守卫

Angular CLI提供了命令行工具,可以快速创建路由守卫框架文件:ng generate guard auth。 执行后,Angular CLI会问我们需要实现哪些接口,我们直接勾选即可:

? Which interfaces would you like to implement? (Press  to select,  to toggle all,  to invert selection)>(*) CanActivate ( ) CanActivateChild ( ) CanDeactivate ( ) CanLoad

说明:

比较经常使用的是1、3,分别控制进入和退出。 按照上面配置,AngularCLI自动生成如下代码,return true; 替换为我们实际的代码即可。return false; 表示不允许跳转,或者取消离开当前页面。

// auth.guard.tsimport { Injectable } from '@angular/core';import { CanActivate, CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';import { Observable } from 'rxjs';@Injectable({  providedIn: 'root'})export class AuthGuard implements CanActivate, CanDeactivate {  canActivate(    route: ActivatedRouteSnapshot,    state: RouterStateSnapshot): Observable | Promise | boolean | UrlTree {    return true;  }}

在canActivate方法中,我们还可以使用跳转。如页面判断是否已经登录,如果没有登录,跳转到Login页面:

this.router.navigate(['/login']);return false;

2. 控制路由是否可以激活

控制路由是否可以激活,需要定义在定义路由的地方,增加canActivate属性。如果需要,还可以增加data属性, 比如告诉我们的AuthGuard进入当前路由需要验证哪些权限。data属性是可选的。

const routes: Routes = [  {    path: "page1",    component: Page1Component,    data: { permissions: ['YourPage1Permission'] },  // 传入参数给AuthGuard,可选    canActivate: [AuthGuard]  },  {    path: "page2",    component: Page2omponent,    data: { permissions: ['YourPage2Permission'] },  // 传入参数给AuthGuard,可选    canActivate: [AuthGuard]  }]

3. 控制路由是否退出(离开)

和控制路由是否可以激活类似,在路由定义出增加 canDeactivate,并制定相应的Guard守卫即可。这里不再举例

到此,关于"分析Angular路由守卫Route Guards"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!

0