我创建了一个根据权限显示元素的指令,该指令的实现方式是这样的。
<ng-container *appHasAccess="'user.profile'">
<button>Profile</button>
</ng-container>
指令代码是:
import {
Directive,
Input,
OnDestroy,
OnInit,
TemplateRef,
ViewContainerRef,
} from "@angular/core";
import { PermissionsService } from "@core/services/permissions";
import { Subject } from "rxjs";
import { takeUntil } from "rxjs/operators";
@Directive({
selector: "[appHasAccess]",
})
export class HasAccessDirective implements OnInit, OnDestroy {
@Input() appHasAccess: string;
stop$ = new Subject();
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private permissionsService: PermissionsService
) {}
ngOnInit(): void {
this.permissionsService
.checkAuthorization(this.appHasAccess)
.pipe(takeUntil(this.stop$))
.subscribe((authorized) => {
if (authorized) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
});
}
ngOnDestroy() {
this.stop$.next();
}
}
这只适用于页面刷新的情况。谁能帮帮我?
如果我没有理解错的话,你可以在 PermissionService
作为 Subject
. 这样,当当前用户发生变化时,服务就可以发出新的值。
service.ts
export class PermissionsService {
user = '';
private currentUser = new Subject<string>();
public setCurrentUser(user) {
this.user = user;
this.currentUser.next(user);
}
checkAuthorization(): Observable<boolean> {
return this.currentUser.pipe(
map( x => { return x === 'me'; })
)
}
}
在上面的代码中 checkAuthorization
是一个可观测的,你可以在你的 Directive
. 事实上,这段代码和你的代码几乎一样,只是我去掉了参数。
directive.ts
ngOnInit(): void {
this.permissionsService.checkAuthorization()
.pipe(takeUntil(this.stop$))
.subscribe((authorized) => {
this.viewContainer.clear();
if (authorized) {
this.viewContainer.createEmbeddedView(this.templateRef);
}
});
}
请注意,你必须始终清除viewContainer,否则每次都会创建一个新按钮。
请看我根据你的例子做的这个演示。https:/stackblitz.comeditangular -fevt6t