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