隐藏角度2中特定用户所需的菜单项

时间:2018-08-04 10:14:01

标签: angular authentication angular-material angular-flex-layout

我创建了一个有角度的应用程序,其中有一个登录表单,其中已使用service和guard实现了身份验证。

我用用户名和密码定义了一个界面用户。使用此界面在 authentication.service.ts 中,我定义了两个用户 admin user

我还实现了一个名为 authentication.guard.ts 的保护措施,在该保护措施中,我使用了 CanActivate RouteGaurd将用户路由到他可以访问的页面。

在我的应用程序中,只有 admin 用户可以访问管理页面,因此,如果仅管理员登录,则导航至管理页面。如果< strong>用户登录,然后跳过管理页面

,他将被重定向到首页

admin user 登录到应用程序时,将出现一个菜单栏,其中有三个菜单项 Home,AdminActivity,RegisterUser

如果 admin 登录到应用程序,我试图隐藏 AdminActivity 菜单项,如果 user,我试图隐藏 RegisterUser 菜单项登录到应用程序。

我尝试在 app.component.ts 中导入身份验证服务,但无法获取登录的用户名和密码。

有人可以帮助我实现所需的功能吗,在我的应用程序中实现

请访问我的示例应用程序here

2 个答案:

答案 0 :(得分:1)

更新了示例代码HERE

使用BehaviorSubject跟踪用户类型并用于显示/隐藏菜单项。您可以使用它在整个应用程序的不同组件之间进行通信。我删除了一些在Stackblitz中引起错误的代码,但不关注于此。

AuthenticationService中的更改:

userType BehaviorSubject声明为:

  userType: BehaviorSubject<string> = new BehaviorSubject<string>(this.getUserType());

添加了从本地存储获取用户类型的方法,

  getUserType() {
    return localStorage.getItem('user')
  }

登录时更新userType BehaviorSubject

login(username, password) {
...
localStorage.setItem("user", this.user.username);
this.userType.next(this.user.username);

app.componet.ts中的更改:

订阅userType BehaviorSubject

  userType: string = '';

  ngOnInit(){
    ...
    this.authService.userType.subscribe(value => this.userType = value);
  }

app.componet.html中的更改:

显示/隐藏带有*ngIf的菜单项:

  <button *ngIf="userType === 'admin'" mat-raised-button routerLink='application/AdminAccess/admin-activity' routerLinkActive="active">Admin Activity </button>

  <button *ngIf="userType === 'user'" mat-raised-button routerLink='application/UserManagement/add-users' routerLinkActive="active">Register User</button>

答案 1 :(得分:0)

由于您的stackbliz无法正常工作,但是在下面,我想提供一些有用的代码:-

在您的routing.module.ts中,修改“管理员”路由,

{path:'Admin',component: AdminComponent,
data: {
    authorities: ['ROLE_ADMIN'],
},
canActivate: [AuthenticationGuard]}

在您的authenticationguard.guard.ts中,进行如下修改:-

 constructor( private auth: AuthenticationService,  private _router: Router) {} 
    
 

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

        const authorities = route.data['authorities'];
        // here you get authorities user role name, now you can apply your service logic
         if (!this.auth.isSuperAdmin(authorities)) { // add arg in isSuperAdmin to validate username
      this._router.navigate(['/application/home']);
      return false; 
    }
    
    return true;
    }

希望这会有所帮助。