32 lines
1.2 KiB
TypeScript
32 lines
1.2 KiB
TypeScript
import { Directive, ViewContainerRef,TemplateRef,OnInit,Input, OnDestroy } from '@angular/core';
|
|
import { Store} from '@ngrx/store';
|
|
import * as appCommonReducer from '../../reducers/app-common.reducer'
|
|
import { Observable, Subscription } from 'rxjs';
|
|
import { IUser } from '../../models/user';
|
|
|
|
@Directive({
|
|
selector: '[fmHasRole]',
|
|
})
|
|
export class HasRoleDirective implements OnInit, OnDestroy{
|
|
@Input('fmHasRole') role:string;
|
|
|
|
constructor(private templateRef$: TemplateRef<any>,private viewContainerRef$: ViewContainerRef,private store$: Store<appCommonReducer.State>) { }
|
|
private user$:Observable<IUser> = this.store$.select(appCommonReducer.SelectGetUser);
|
|
private hasView = false;
|
|
private roleClaim = 'role';
|
|
private sub: Subscription;
|
|
ngOnInit() {
|
|
this.sub = this.user$.subscribe((user) => {
|
|
if (user && user.claims[this.roleClaim]?.includes(this.role)) {
|
|
this.viewContainerRef$.createEmbeddedView(this.templateRef$);
|
|
this.hasView=true;
|
|
} else if (this.hasView) {
|
|
this.viewContainerRef$.clear();
|
|
this.hasView = false;
|
|
}
|
|
});
|
|
}
|
|
ngOnDestroy() {
|
|
if (this.sub) {this.sub.unsubscribe() }
|
|
}
|
|
} |