【发布时间】:2017-02-13 19:50:07
【问题描述】:
我有一个登录/注销的 AuthService,检查用户是否已登录并使用 angular2-jwt(例如使用 tokenNotExpired())。
我只为此服务创建了一个模块以将其用作单例。
现在我检查用户是否登录,例如:
<p *ngIf="authService.authenticated()">Text</p>
按预期工作。
现在我想要实现的是将此*ngIf 包装到自己的指令中,以便检查用户是否登录的组件不必注入 AuthService。
基本上是这样的:
<p *authenticated>Text</p>
我已经像这样创建了经过身份验证的指令:
@Directive({selector: "[authenticated]"})
export class AuthenticatedDirective {
constructor(private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private auth: AuthService) {
}
@Input() set authenticated(condition: boolean) {
if (this.auth.authenticated()) {
console.log("IsLoggedIn");
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
console.log("NotLoggedIn");
this.viewContainer.clear();
}
}
}
它基本上是*ngIf指令,只是它不使用参数。
问题是它只在站点加载时被调用,它不会定期检查this.auth.authenticated() 以查看令牌是否已过期。
如果指令不监听它,触发更改检测当然不会做任何事情,因此手动触发(例如,在注销后)它不起作用。
我知道您可以“监听”(使用主机或 HostListeners)指令中的事件,但我找不到用于更改检测的事件,我可以使用它触发指令“更新”。
所以基本上我的问题是,我该如何收听更改检测事件,或者是否有更好的解决方案来包装这个*ngIf="authService.authenticated()"?
提前致谢。
更新:
随着@Chrillewoodz 的评论,我终于想起了生命周期钩子,尤其是提到的 DoCheck。
我目前对该指令的解决方案是这样的:
@Directive({selector: "[authenticated]"})
export class AuthenticatedDirective implements DoCheck {
private isAuthenticated = false;
constructor(private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private auth: AuthService) {
}
ngDoCheck() {
if (this.isAuthenticated !== this.auth.authenticated()) {
this.isAuthenticated = this.auth.authenticated();
if (this.auth.authenticated()) {
console.log("IsLoggedIn");
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
console.log("NotLoggedIn");
this.viewContainer.clear();
}
}
}
}
【问题讨论】:
-
DoCheck可能是您的解决方案。
标签: angular typescript angular2-directives