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

Angular-14侧边栏菜单角色权限配置实现方法问询

Angular 14 侧边栏菜单权限控制实现方案

1. 改造 sidebar.ts 定义带权限的菜单列表

在组件里定义菜单结构,给每个菜单项指定允许访问的角色集合,同时从 localStorage 获取当前用户角色,最后过滤出符合权限的菜单:

import { Component, OnInit } from '@angular/core';

// 定义菜单接口,包含权限字段
interface MenuItem {
  title: string;
  icon: string;
  route: string;
  allowedRoles: string[];
}

@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.css']
})
export class SidebarComponent implements OnInit {
  userRole: string | null = '';
  filteredMenuItems: MenuItem[] = [];

  // 完整的菜单配置(含权限规则)
  private allMenuItems: MenuItem[] = [
    {
      title: 'Dashboard',
      icon: 'dashboard',
      route: '/dashboard',
      allowedRoles: ['Admin', 'Teacher', 'Student'] // 所有角色可见
    },
    {
      title: 'Student List',
      icon: 'people',
      route: '/students',
      allowedRoles: ['Admin', 'Teacher'] // 仅管理员、教师可见
    },
    {
      title: 'Fee List',
      icon: 'receipt',
      route: '/fees',
      allowedRoles: ['Admin'] // 仅管理员可见
    },
    {
      title: 'My Fees',
      icon: 'account_balance_wallet',
      route: '/my-fees',
      allowedRoles: ['Student'] // 仅学生可见
    }
  ];

  ngOnInit(): void {
    // 获取当前用户角色
    this.userRole = localStorage.getItem('role');
    // 过滤出当前角色有权限访问的菜单
    this.filteredMenuItems = this.allMenuItems.filter(item => {
      // 处理角色为空的情况(比如未登录)
      if (!this.userRole) return false;
      return item.allowedRoles.includes(this.userRole);
    });
  }
}

2. 改造 sidebar.html 渲染过滤后的菜单

直接遍历过滤后的菜单数组,不符合权限的菜单项已被提前过滤,无需额外判断:

<mat-nav-list>
  <a mat-list-item *ngFor="let item of filteredMenuItems" [routerLink]="item.route">
    <mat-icon matListItemIcon>{{ item.icon }}</mat-icon>
    <div matListItemTitle>{{ item.title }}</div>
  </a>
</mat-nav-list>

补充说明

  • 加入了角色空值处理,避免未登录或角色不存在时出现逻辑错误
  • 后续调整权限只需修改 allMenuItems 里的 allowedRoles 数组,无需改动模板代码
  • 若要提升代码复用性,可把权限判断逻辑抽成独立的 AuthService,供多个组件调用

内容的提问来源于stack exchange,提问作者Ayobamilaye

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 02:10:37