根据用户显示选项



我有 3 个用户管理员、主管和学生。我想做的是,管理员和主管可以编辑和删除学生数据,而学生只能删除和编辑自己的数据。他只能查看其他人的数据。

我在 json 中获取用户的角色,如下所示:

Admin: ["Administrator"]
Supervisor: ["Supervisor", "Guest"]
Student: ["Student", "Guest"]

以下是我正在尝试做的事情:

展品.组件.ts

getCurrentUser() {
this.userService.getCurrent()
.then(
(response) => {
this.currentUserId = response.id;
for (let role of response.roles) {
if (role === 'Administrator') {
this.canEdit = true;
} else if (role === 'Supervisor') {
this.canEdit = true;
} else if (role === 'Student') {
this.canEdit = false;
}
}
}
).catch(
(error) => console.log(error)
);
}

展品.html

<div *ngIf="canEdit && this.currentUserId === exhibit.userId">
<button md-icon-button click-stop-propagation color="primary" [routerLink]="['/mobile-content/exhibits/edit', exhibit.id]"
title="{{ 'edit' | translate }}">
<md-icon>{{ !inDeletedPage ? 'edit' : 'remove_red_eye'}}</md-icon>
</button>
<button md-icon-button click-stop-propagation color="warn" (click)="deleteExhibit(exhibit)" *ngIf="!exhibit.used && !inDeletedPage"
title="{{ 'delete' | translate }}">
<md-icon>delete_forever</md-icon>
</button>
</div>

正在尝试显示我根据userId在数组中获得的展品。这意味着,在展示 json 响应中,我正在获取"userId",我正在尝试将其与当前用户的用户 ID 匹配。Oly的事情是学生只能看到他创建的展览的删除和编辑选项,但管理员和主管可以看到所有用户创建的展览的编辑和删除选项。

谁能帮我弄清楚这一点?

首先,我建议将其转换为前端和后端的枚举,而不是依赖字符串匹配。

但是从您的代码来看,如果我阅读正确,没有学生能够拥有编辑和删除按钮,因为您始终在该用户类型上设置为 false。

你的第二个问题将出现在你的*ngIf中,它陈述了以下内容:

*ngIf="canEdit && this.currentUserId === exhibit.userId"

这将导致这些按钮始终在不需要的时间被隐藏,因为即使在管理员和其他用户上,您也需要用户 ID 匹配的条件才能计算为 true。您也不需要在模板中指定this

就个人而言,我会做更多这样的事情。

getCurrentUser() {
this.userService.getCurrent()
.then(
(response) => {
this.currentUserId = response.id;
for (let role of response.roles) {
if (role === 'Administrator') {
this.canEdit = true;
} else if (role === 'Supervisor') {
this.canEdit = true;
} else if (role === 'Student') {
if (this.currentUserId === this.exhibit.userId) {
this.canEdit = true;
} else {
this.canEdit = false;
}
}
}
}
).catch(
(error) => console.log(error)
);
}

然后,您只需将模板 *ngIf 更改为:

*ngIf="canEdit"

顺便说一句,您可能还希望将角色的检查更改为 switch 语句,它的性能更高,并且会使您的代码更清晰。

或者你可以这样做,这将完成同样的事情。

getCurrentUser() {
this.userService.getCurrent()
.then(
(response) => {
this.currentUserId = response.id;
for (let role of response.roles) {
if (role === 'Administrator') {
this.canEdit = true;
} else if (role === 'Supervisor') {
this.canEdit = true;
}
}
}
).catch(
(error) => console.log(error)
);
}

模板代码将是:

*ngIf="canEdit || this.currentUserId === exhibit.userId"

最新更新