typescript 如何根据用户角色 Angular 4 显示/隐藏元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49050425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to show/hide element depending on user role Angular 4
提问by Mohamed Wahshey
I'm working on a project which has more than one user type (SuperUser - SchoolAdmin - Teacher)
我正在开发一个具有多个用户类型的项目(超级用户 - 学校管理员 - 教师)
And each role has privilige to see some elements.
每个角色都有特权看到一些元素。
How do i hide elements depending on the logged user role using *ngIf?
如何使用 *ngIf 根据登录的用户角色隐藏元素?
This is the project linkon Stack-blitz, i uploaded some of it to guide me with the live preview.
这是Stack-blitz 上的项目链接,我上传了其中的一些来指导我进行实时预览。
Inside app you will find common services >> auth, this is the folder which has login service and authentication guard.
在app里面你会发现common services >> auth,这是有登录服务和认证保护的文件夹。
Inside models >> enum, you will find user type enum.
在models >> enum里面,你会发现用户类型enum。
Inside component sign-in you will find the form which defines user type.
在组件登录中,您将找到定义用户类型的表单。
Inside routes you will see the expected roles made for each component.
在路由内部,您将看到为每个组件制定的预期角色。
Users that i made for testing:
我为测试而创建的用户:
This should route you to the school-list
这应该将您路由到学校列表
Admin (which has super user role): [email protected] Password: 12345
管理员(具有超级用户角色):[email protected] 密码:12345
This should route you to the dashboard
这应该将您路由到仪表板
Student (which has student role): [email protected] Password: 12345
学生(有学生角色):[email protected] 密码:12345
For example is i want to hide element on the dash-board to be only shown to the super user role, how can i do this?
例如,我想隐藏仪表板上的元素,只显示给超级用户角色,我该怎么做?
I know that there is a way with ngIf but i'm stuck on the right way to write it inside the NgIf, i want examples on my code not a dummy code.
我知道 ngIf 有一种方法,但我坚持在 NgIf 中编写它的正确方法,我想要我的代码示例而不是虚拟代码。
Update: issue has been resolved so i deleted the users made for testing.
更新:问题已解决,因此我删除了用于测试的用户。
回答by carton
In your project, when a user is registering you are asking if he is a 'Teacher', 'Parent' or a 'Student'. So here you have your condition.
在您的项目中,当用户注册时,您会询问他是“老师”、“家长”还是“学生”。所以这里有你的条件。
When you sign-in or register you should save your user data somewhere (in a service for exemple which you can use with @injection.
当您登录或注册时,您应该将您的用户数据保存在某处(例如,在您可以与@injection 一起使用的 服务中)。
Then with that data you should make some test in your DOM like this:
然后使用这些数据,您应该像这样在 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>
Is this helping you ? You should read this docs Services
这对你有帮助吗?您应该阅读此文档服务
[Exemple in your case]
【你的例子】
Your service:
您的服务:
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;
}
}
Then inject that service in your constructor and your service in
然后在您的构造函数中注入该服务,并将您的服务注入
Component:
零件:
// Don't forgot to import UserService !!
constructor(public userService: UserService){}
DOM:
DOM:
*ngIf="userService.currentUser.type_id == 1"
回答by Joe Belladonna
You should do:
你应该做:
<div *ngIf="superUserLogged">
// your SuperUser display ...
</div>
<div *ngIf="schoolAdminLogged">
// your SuperUser display ...
</div>
<div *ngIf="teacherLogged">
// your SuperUser display ...
</div>
and in *.ts file when ever someone logs to system you do:
并在 *.ts 文件中,当有人登录系统时,您会执行以下操作:
onLogin(userrLogged: string) {
this.superUserLogged = false;
this.schoolAdminLogged = false;
this.teacherLogged = false;
switch (userrLogged) {
case 'SuperUser':
this.superUserLogged = true;
break;
case 'SchoolAdmin':
this.schoolAdminLogged = true;
break;
case 'Teacher':
this.teacherLogged = true;
break;
}
回答by Sangeeth John
boolean value true or false is used for hiding. In HTML file <div *ngIf = !test>_contents to be printed_</div>
In .ts file initialize test = false;
so whenever this.test = true;
div will show otherwise will be in hide . Check your condition and make the test = true;
布尔值 true 或 false 用于隐藏。在 HTML 文件中, <div *ngIf = !test>_contents to be printed_</div>
在 .ts 文件中进行初始化,test = false;
因此每当this.test = true;
div 显示时,否则将在 hide 中。检查您的状况并制作test = true;