Angular 的路由守卫(Routing Guard)是用于在 Angular 应用程序中控制路由访问权限的一种机制。它允许你根据用户的角色、权限或其他条件来决定是否允许用户访问特定的路由。

路由守卫的类型

  • CanActivate:确保用户可以访问特定的路由。
  • CanActivateChild:确保可以访问子路由。
  • CanDeactivate:确保在离开当前路由之前执行某些操作。
  • Resolve:在路由激活之前获取数据。

如何使用路由守卫

  1. 创建路由守卫类

    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 {
        if (localStorage.getItem('isLoggedIn')) {
          return true;
        } else {
          this.router.navigate(['/login']);
          return false;
        }
      }
    }
    
  2. 在路由配置中使用守卫

    const routes: Routes = [
      { path: 'admin', component: AdminComponent, canActivate: [AuthGuard] }
    ];
    

图片示例

Angular Routing

更多信息

想要了解更多关于 Angular 路由守卫的信息,可以访问我们的Angular 路由守卫教程