在本教程中,我们将看到如何在Angular 9中基于用户角色显示或查看组件。不仅仅是组件,它还可以应用于HTML的每个元素。
在具有多个用户角色的任何应用程序中,您可能都会遇到一个场景,以显示和隐藏DOM中的组件或元素来处理这种场景,我们可以创建一个 指示 like a *ngIf
so let’s create it.
话题
- 按用户角色划分的组件
- 用户角色服务 (可选的)
- 创建要显示和隐藏的指令
- 演示版
根据用户角色查看组件
首先让我们了解我们的指令如何与模板一起使用。
一个应用程序可以基于单个或多个用户角色。因此,该指令将接受其中可以定义多个用户角色的数组属性。
app.component.html
<!-- Display only for Admin -->
<app-some-component *ifRoles='["Admin"]'> ... </app-some-component>
<!-- Display only for Admin & SuperAdmin -->
<app-some-component *ifRoles='["Admin", "SuperAdmin"]'> ... </app-some-component>
<!-- *ifRoles : using on HTML Elements -->
<section *ifRoles='["User"]'> ... </section>
用户角色指令如何工作
- 如果用户具有指令选择器中提到的适当角色,则应在DOM中添加组件。
- 如果用户没有适当的角色来查看特定内容,则应从DOM中删除该组件或元素。
It will behave similarly to *ngIf='true'
or *ngIf='false'
we use in angular.
用户角色服务
对于角色,我们必须具有为我们提供用户角色列表的服务。为了证明我已经使用了 www.jsonbin.io 该站点存储一些静态数据以使演示工作。
//api.jsonbin.io/b/5eca9addbbaf1f2589463bbf - (Dummy API for USer Roles)
API响应
{
"roles": [
"Admin",
"SuperAdmin",
"User",
"DataManager"
]
}
根据用户角色显示和隐藏的指令
我们首先使用angular CLI命令生成指令
重击
ng generate 指示 IfRoles
并且我们的指令将具有这样的内容。
ifRoles.directive.ts
import { Input, OnInit, Directive, ViewContainerRef, TemplateRef, OnDestroy } from "@angular/core";
import { Subject, Subscription } from "rxjs";
import { takeUntil } from "rxjs/operators";
import { RolesService } from "../services/roles.service";
@Directive({
selector: '[ifRoles]'
})
export class IfRolesDirective implements OnInit, OnDestroy {
private subscription: Subscription[] = [];
// the role the user must have
@Input() public ifRoles: Array<string>;
/**
* @param {ViewContainerRef} viewContainerRef -- the location where we need to render the templateRef
* @param {TemplateRef<any>} templateRef -- the templateRef to be potentially rendered
* @param {RolesService} rolesService -- will give us access to the roles a user has
*/
constructor(
private viewContainerRef: ViewContainerRef,
private templateRef: TemplateRef<any>,
private rolesService: RolesService
) {}
public ngOnInit(): void {
this.subscription.push(
this.rolesService.roles().subscribe(res => {
if (!res.roles) {
// Remove element from DOM
this.viewContainerRef.clear();
}
// user Role are checked by a Roles mention in DOM
const idx = res.roles.findIndex((element) => this.ifRoles.indexOf(element) !== -1);
if (idx < 0) {
this.viewContainerRef.clear();
} else {
// appends the ref element to DOM
this.viewContainerRef.createEmbeddedView(this.templateRef);
}
})
);
}
/**
* on destroy cancels the API if its fetching.
*/
public ngOnDestroy(): void {
this.subscription.forEach((subscription: Subscription) => subscription.unsubscribe());
}
}
this.templateRef
contains the DOM refrence inside theifRoles
selector.viewContainerRef.clear()
如果用户角色不匹配,将从DOM中删除内容。viewContainerRef.createEmbeddedView(templateRef)
如果用户角色匹配,将追加DOM。
演示版
获取有关的更多教程 角度9+