MST
星途 面试题库

面试题:Angular路由守卫之CanActivate解析

请阐述Angular中CanActivate路由守卫的作用,并且说明如何在一个组件路由中使用CanActivate来实现权限控制,假设只有特定角色的用户才能访问该组件,写出关键代码示例。
42.3万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

CanActivate路由守卫的作用

在Angular中,CanActivate路由守卫用于在导航到某个路由之前进行权限验证。它允许开发者在用户尝试访问特定路由时,决定是否允许该导航操作。这在实现权限控制、用户认证等场景中非常有用,确保只有满足特定条件(如已登录、具有特定角色等)的用户才能访问相应的路由组件。

在组件路由中使用CanActivate实现权限控制的关键代码示例

  1. 创建路由守卫服务
    import { Injectable } from '@angular/core';
    import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
    // 假设这里有一个模拟的认证服务
    import { AuthService } from './auth.service'; 
    
    @Injectable({
      providedIn: 'root'
    })
    export class RoleGuardService implements CanActivate {
    
      constructor(private authService: AuthService, private router: Router) {}
    
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        const expectedRole = route.data['expectedRole'];
        const userRole = this.authService.getUserRole();
    
        if (userRole === expectedRole) {
          return true;
        } else {
          this.router.navigate(['/forbidden']);
          return false;
        }
      }
    }
    
  2. 配置路由并使用守卫
    import { NgModule } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    import { MyComponent } from './my.component';
    import { RoleGuardService } from './role - guard.service';
    
    const routes: Routes = [
      {
        path: 'my - component',
        component: MyComponent,
        canActivate: [RoleGuardService],
        data: {
          expectedRole: 'admin' // 假设只有admin角色能访问
        }
      }
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule {}
    
  3. 模拟的认证服务(仅为示例)
    import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root'
    })
    export class AuthService {
    
      private userRole = 'admin'; // 模拟用户角色,实际应从后端获取或存储在本地
    
      getUserRole() {
        return this.userRole;
      }
    }
    

上述代码首先创建了一个RoleGuardService路由守卫服务,在canActivate方法中检查用户角色是否与路由配置中期望的角色匹配。然后在路由配置中,对MyComponent组件的路由使用了该守卫,并指定了期望的用户角色。最后是一个简单的模拟认证服务,用于获取用户角色。