繁体   English   中英

根据角色显示/隐藏组件

[英]show/hide components based on roles

我有一个仪表板组件,将提供不同的配置文件。 对于每个配置文件,我创建了一个单独的组件并将其添加到主仪表板组件:

**dashboard.component.html**

<app-employer-dashboard></app-employer-dashboard>
<app-candidate-dashboard></app-candidate-dashboard>

我要实现的功能类似于路由的身份验证保护,添加一些装饰,以便基于用户个人资料仅激活相应的组件。 使用[hidden]="hasNotAccessToComponent()"似乎是可能的,但我想知道是否还有一种更优雅的方法。

我建议使用route Guards在带有canActivate属性的路由器中对其进行设置,如下所示:

因此,您的路线将是-

const routes: Routes = [
    {
        path: 'employer',
        component: EmployerDashboardComponent,
        canActivate: [AuthGuard]
    },
    {
        path: 'candidate',
        component: CandidateDashboardComponent,
        canActivate: [AuthGuard]
    }
];

您在AuthGuard中的 canActivate方法将类似于以下内容-

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    const currentUser = this.userService.getCurrentUser();
    this.currentUserRole = currentUser ? JSON.parse(currentUser)['role'] : undefined;
    this.currentUserRole = this.currentUserRole ? this.currentUserRole.toLowerCase() : undefined;

    // I stored allowed paths with the same user object
    let allowedPaths = currentUser ? JSON.parse(currentUser)['allowedPaths'] : undefined;

    // obtaining an array of strings for allowed paths
    this.allowedPaths = allowedPaths ? allowedPaths.split(",").map(Function.prototype.call, String.prototype.trim) : undefined;
    const isLoggedIn = this.userService.isLoggedIn();
    if(isLoggedIn) {
        if (this.currentUserRole == 'admin') {
            return true;
        } else {
            return this.validatePath(this.allowedPaths, state.url);
        }
    } else {
        return false;
    }
}

我用来validatePath的方法如下:

validatePath(pathArray: Array <string>, path: string): boolean {
    if(!pathArray) {
        return false;
    }

    if(pathArray.includes(path)) {
        return true;
    } else {
        this.router.navigate(['inaccessible']);
        return false;
    }
}

暂无
暂无

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

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