繁体   English   中英

Angular - 如何在侧边菜单应用用户角色权限

[英]Angular - How to apply user roles permission on the side menu

在我的 Angular-14 应用程序中,我有来自 API 的这些角色:

  1. 行政
  2. 老师
  3. 学生

我使用 userRole = localStorage.getItem('role') 来显示它。 每个用户只能有一个角色。

我想将角色应用到侧边栏,这样只有指定的角色才能看到允许的菜单。

侧边栏.ts:

export class SidebarComponent implements OnInit {
  @HostBinding('class') classes: string = BASE_CLASSES;
  public menu = MENU;
  userRole = localStorage.getItem('role');

  constructor(
  ) {}

  ngOnInit() {

  }

}
export const MENU = [
  {
      name: 'Dashboard',
      iconClasses: 'fas fa-tachometer-alt',
      path: ['/admin-dashboard']
  },
  {
      name: 'Student List',
      iconClasses: 'fas fa-users',
      path: ['/admin-dashboard/students-list']
  },
  {
    name: 'Payments',
    iconClasses: 'fas fa-calendar',
    children: [
        {
            name: 'Fee List',
            iconClasses: 'far fa-circle nav-icon',
            path: ['/admin-dashboard/fee-list']
        },
        {
            name: 'My Fees',
            iconClasses: 'far fa-circle nav-icon',
            path: ['/admin-dashboard/myfees']
        }
    ]
  }
];

侧边栏.html:

  <nav class="mt-2" style="overflow-y: hidden">
      <ul
          class="nav nav-pills nav-sidebar flex-column"
          data-widget="treeview"
          role="menu"
          data-accordion="false"
      >
          <app-menu-item
              *ngFor="let item of menu"
              [menuItem]="item"
          ></app-menu-item>
      </ul>
  </nav>

我想实现这些:

  1. 所有用户查看仪表板
  2. 只有管理员和老师才能查看学生列表
  3. 只有管理员才能查看费用清单
  4. 只有学生可以查看我的费用

如何应用 userRole() 来实现这一点?

谢谢

您仍然希望查看路线守卫以锁定实际路线,但您可以有条件地添加菜单项

export class SidebarComponent implements OnInit {
  @HostBinding('class') classes: string = BASE_CLASSES;
  userRole = localStorage.getItem('role') as "admin" | "teacher" | "student";
  public menu = [
    {
        name: 'Dashboard',
        iconClasses: 'fas fa-tachometer-alt',
        path: ['/admin-dashboard']
    },
    ...(this.userRole === "admin" || this.userRole === "teacher" ? [{
        name: 'Student List',
        iconClasses: 'fas fa-users',
        path: ['/admin-dashboard/students-list']
    }] : []), 
    ...(this.userRole === "admin" || this.userRole === "student" ? [{
      name: 'Payments',
      iconClasses: 'fas fa-calendar',
      children: [
          ...(this.userRole === "admin" ? [{
              name: 'Fee List',
              iconClasses: 'far fa-circle nav-icon',
              path: ['/admin-dashboard/fee-list']
          }] : []),
          ...(this.userRole === "student" ? [{
              name: 'My Fees',
              iconClasses: 'far fa-circle nav-icon',
              path: ['/admin-dashboard/myfees']
          }] : [])
      ]
    }] : [])
  ];

  constructor(
  ) {}

  ngOnInit() {
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM