fix(console): remove redundancy in hasrole directive (#4063)

Co-authored-by: Livio Spring <livio.a@gmail.com>
This commit is contained in:
Max Peintner 2022-07-29 07:13:15 +02:00 committed by GitHub
parent 8448f88f94
commit fb52575f79
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,25 +1,34 @@
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { Directive, Input, OnDestroy, TemplateRef, ViewContainerRef } from '@angular/core';
import { Subject, takeUntil } from 'rxjs';
import { GrpcAuthService } from 'src/app/services/grpc-auth.service';
@Directive({
selector: '[cnslHasRole]',
})
export class HasRoleDirective {
export class HasRoleDirective implements OnDestroy {
private destroy$: Subject<void> = new Subject();
private hasView: boolean = false;
@Input() public set hasRole(roles: string[] | RegExp[] | undefined) {
if (roles && roles.length > 0) {
this.authService.isAllowed(roles).subscribe((isAllowed) => {
if (isAllowed && !this.hasView) {
this.viewContainerRef.clear();
this.viewContainerRef.createEmbeddedView(this.templateRef);
} else {
this.viewContainerRef.clear();
this.hasView = false;
}
});
this.authService
.isAllowed(roles)
.pipe(takeUntil(this.destroy$))
.subscribe((isAllowed) => {
if (isAllowed && !this.hasView) {
if (this.viewContainerRef.length !== 0) {
this.viewContainerRef.clear();
}
this.viewContainerRef.createEmbeddedView(this.templateRef);
} else {
this.viewContainerRef.clear();
this.hasView = false;
}
});
} else {
if (!this.hasView) {
this.viewContainerRef.clear();
if (this.viewContainerRef.length !== 0) {
this.viewContainerRef.clear();
}
this.viewContainerRef.createEmbeddedView(this.templateRef);
}
}
@ -30,4 +39,9 @@ export class HasRoleDirective {
protected templateRef: TemplateRef<any>,
protected viewContainerRef: ViewContainerRef,
) {}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}