You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular路由守卫实现RBAC时遇TypeError:include不是函数

Angular守卫实现RBAC时的include方法错误解决

问题重现

在实现基于角色的访问控制(RBAC)守卫时,触发如下报错:

core.mjs:8400 ERROR Error: Uncaught (in promise): TypeError: this.authService.roles.include is not a function
TypeError: this.authService.roles.include is not a function

对应守卫代码如下:

import { Injectable } from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router';
import { Observable } from 'rxjs';
import {AuthentificationService} from "../services/authentification.service";

@Injectable({
  providedIn: 'root'
})
export class AuthorizationGuard implements CanActivate {
  constructor(private authService : AuthentificationService, private router : Router) {
  }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if(this.authService.roles.include("ADMIN")){
      return true;
    }else{
      this.router.navigateByUrl("/admin/notAuthorized")
      return false;
    }
  }
}

错误原因

JavaScript数组判断元素是否存在的方法是includes()(注意末尾的s),而非include(),属于方法名拼写错误。此外,未处理this.authService.roles为null或undefined的情况,可能触发额外空指针错误。

修正后的代码

import { Injectable } from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router';
import { Observable } from 'rxjs';
import {AuthentificationService} from "../services/authentification.service";

@Injectable({
  providedIn: 'root'
})
export class AuthorizationGuard implements CanActivate {
  constructor(private authService : AuthentificationService, private router : Router) {
  }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    // 先判断roles是否存在,再调用正确的includes方法
    if(this.authService.roles?.includes("ADMIN")){
      return true;
    }else{
      this.router.navigateByUrl("/admin/notAuthorized");
      return false;
    }
  }
}

扩展优化:通用角色守卫

若需支持多路由的不同角色校验,可将角色配置在路由data属性中,让守卫更通用:

  1. 路由配置示例:
const routes: Routes = [
  {
    path: 'admin/dashboard',
    component: AdminDashboardComponent,
    canActivate: [AuthorizationGuard],
    data: { requiredRoles: ['ADMIN', 'SUPER_ADMIN'] } // 配置路由所需角色
  },
  {
    path: 'user/profile',
    component: UserProfileComponent,
    canActivate: [AuthorizationGuard],
    data: { requiredRoles: ['USER', 'ADMIN'] }
  }
];
  1. 优化后的守卫代码:
canActivate(
  route: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
  const requiredRoles = route.data['requiredRoles'] as string[];
  if (!requiredRoles || requiredRoles.length === 0) {
    return true; // 无角色要求直接放行
  }

  // 判断用户角色与要求角色是否存在交集
  const hasPermission = this.authService.roles?.some(role => requiredRoles.includes(role)) ?? false;
  
  if (hasPermission) {
    return true;
  } else {
    this.router.navigateByUrl("/admin/notAuthorized");
    return false;
  }
}

内容的提问来源于stack exchange,提问作者Sirat Ben jemaa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 15:15:04