如何根据用户角色 Angular 4 显示/隐藏元素

Moh*_*hey 1 authentication user-roles typescript angular-ng-if angular

我正在开发一个具有多个用户类型的项目(超级用户 - 学校管理员 - 教师)

每个角色都有特权看到一些元素。

如何使用 *ngIf 根据登录的用户角色隐藏元素?

这是Stack-blitz 上的项目链接,我上传了其中的一些内容来指导我进行实时预览。

在app里面你会发现common services >> auth,这是有登录服务和认证保护的文件夹。

在models >> enum 里面,你会发现用户类型enum。

在组件登录中,您将找到定义用户类型的表单。

在路由内部,您将看到为每个组件制定的预期角色。

我为测试而创建的用户:

这应该将您路由到学校列表

管理员(具有超级用户角色):test1@test.com 密码:12345

这应该将您路由到仪表板

学生(有学生角色):test2@test.com 密码:12345

例如,我想隐藏仪表板上的元素,只显示给超级用户角色,我该怎么做?

我知道 ngIf 有一种方法,但我坚持在 NgIf 中编写它的正确方法,我想要我的代码示例而不是虚拟代码。

更新:问题已解决,因此我删除了用于测试的用户。

car*_*ton 5

在您的项目中,当用户注册时,您会询问他是“老师”、“家长”还是“学生”。所以这里有你的条件。

当您登录或注册时,您应该将您的用户数据保存在某处(例如,在您可以与@injection 一起使用的 服务中)

然后使用这些数据,您应该像这样在 DOM 中进行一些测试:

/* if type_id == id(student) */
 <div *ngIf="myService.currentUser.type_id">
   // your student display ...
 </div>

 /* if type_id == id(teacher) */
 <div *ngIf="myService.currentUser.type_id">
   // your teacher display ...
 </div>
Run Code Online (Sandbox Code Playgroud)

这对你有帮助吗?您应该阅读此文档服务

【你的例子】

您的服务:

import { Injectable } from '@angular/core';
/*
   other import 
*/

 @Injectable()
 export class UserService {

      public currentUser: any;

      constructor(){}

      public login(loginData: LoginModel): any {
            const apiUrl: string = environment.apiBaseUrl + '/api/en/users/login';  
            let promise = new Promise((resolve, reject) => { // this is a  promise. learn what is a promise in Javascript. this one  is only more structured in TypeScript
  // a promise is returned to make sure that action is taken only after the response to the api is recieved
             this.http.post(apiUrl, loginData).subscribe((data: any) => {
                if(data.status)
                {
                  var userData = {
                      token: data.token,
                      user:data.user 
                     };
                this.currentUser = data.user // HERE SAVE YOUR user data
                return resolve(userData);
                }
                else {
                       return reject(data)
                 }
               }, (err: HttpErrorResponse) => {
               return reject(err);
            });
          });
     return promise;
      }
 }
Run Code Online (Sandbox Code Playgroud)

然后在您的构造函数中注入该服务,并将您的服务注入

成分:

// Don't forgot to import UserService !!
constructor(public userService: UserService){}
Run Code Online (Sandbox Code Playgroud)

DOM:

*ngIf="userService.currentUser.type_id == 1"
Run Code Online (Sandbox Code Playgroud)