在我的应用程序中,我有一个具有权限数组的帐户服务,所以我创建了一个结构指令来决定是否显示一个操作按钮,但问题是当我登录/注销并更新权限数组时,指令不会更新视图。
这是代码:
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { Account } from './models';
import { AccountService } from './account.service';
@Directive({
selector: '[appAuth]',
})
export class AuthDirective {
@Input() set appAuth(action: string) {
if (this._account.permissions.includes(action)) {
this._contRef.createEmbeddedView(this._tmplRef);
} else {
this._contRef.clear();
}
}
constructor(
private _contRef: ViewContainerRef,
private _tmplRef: TemplateRef<any>,
private _account: AccountService
) { }
}
以下是该指令的使用示例:
<button
class="btn btn-default"
*appAuth="'find-accounts'"
(click)="doSomething()">
Find Accounts
</button>
答案 0 :(得分:1)
import { Account, AccountService } from '../common';
import { Subscription } from 'rxjs/Subscription';
import {
Directive, Input, TemplateRef, ViewContainerRef, OnInit, OnDestroy
} from '@angular/core';
@Directive({
selector: '[appAuth]',
})
export class AuthDirective implements OnInit, OnDestroy {
private _accountChangesSubscription: Subscription;
@Input('appAuth') private appAuth: string;
constructor(
private _contRef: ViewContainerRef,
private _tmplRef: TemplateRef<any>,
private _account: AccountService
) { }
ngOnInit() {
this._accountChangesSubscription = this._account.changes$
.subscribe((account: Account) => {
const permissions = this._account.permissions;
if (permissions && permissions.includes(this.appAuth)) {
this._contRef.createEmbeddedView(this._tmplRef);
} else {
this._contRef.clear();
}
});
}
ngOnDestroy() {
this._accountChangesSubscription.unsubscribe();
}
}