[英]Angular - How to apply user roles permission on the side menu
In my Angular-14 application, I have these roles from the API:在我的 Angular-14 应用程序中,我有来自 API 的这些角色:
I use userRole = localStorage.getItem('role') to display this.我使用 userRole = localStorage.getItem('role') 来显示它。 Each user can only have a role.每个用户只能有一个角色。
I want to apply the roles to the sidebar, so that only the specified roles will see the allowed menu.我想将角色应用到侧边栏,这样只有指定的角色才能看到允许的菜单。
sidebar.ts:侧边栏.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']
}
]
}
];
sidebar.html:侧边栏.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>
I want to to achieve these:我想实现这些:
How do I apply userRole() to achieve this?如何应用 userRole() 来实现这一点?
Thanks谢谢
You would still want to look into route guards to lock down the actual route but you can conditionally add menu items您仍然希望查看路线守卫以锁定实际路线,但您可以有条件地添加菜单项
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.