javascript - Angular 6 视图未更新为页面加载时的正确数据
问题描述
我有这个 Angular 6 应用程序,我使用 Firebase 的 Google 登录实现了登录。我添加了一个按钮,当您注销时显示登录,或者如果您已登录,按钮显示注销,它还显示您当前登录的电子邮件地址。
这是一个代码示例:
<p *ngIf="isLoggedIn()" class="text-white" style="margin-bottom: 0; padding-left: 10px">{{ afAuth.auth.currentUser.email }}</p>
<button *ngIf="!isLoggedIn()" class="btn btn-danger" type="button" (click)="login()">Log In</button>
<button *ngIf="isLoggedIn()" class="btn btn-danger" type="button" (click)="logout()">Log Out</button>
constructor(private afAuth: AngularFireAuth) {
}
isLoggedIn() {
return this.afAuth.auth.currentUser;
}
login() {
try {
this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider());
} catch (e) {
console.log(e.message);
}
}
logout () {
try {
this.afAuth.auth.signOut().then(() => {
this.hideAllViews();
});
} catch (e) {
console.log(e.message);
}
}
一切似乎都正常,除了如果您当前已登录并刷新页面,它似乎没有显示正确的状态,这意味着它显示登录按钮而不是显示您的电子邮件地址和注销按钮,因为您已经登录。一旦您单击选项卡或任何其他按钮或链接页面更新回显示电子邮件和注销按钮。
对我来说,似乎 HTML 页面在检查isLoggedIn()方法之前正在加载。
我通过在构造函数中添加以下内容找到了解决方法:
setTimeout(function () {
},
请让我知道解决此问题的“角度方式”/最佳方式是什么。
解决方案
你所做的是一个很好的解决方法,但你应该实际使用的是life cycle hook(s)
例如: ngAfterViewInit
ngAfterViewInit() {
this.isLoggedIn();
}
推荐阅读
- next.js - 什么构成/决定了 Zeit 无服务器功能的数量
- javascript - 在哪里在线上传 javascript 文件以及如何正确获取它?
- highcharts - Highcharts 组织结构图 - 节点显示不正确
- c# - 在 Azure DevOps 上显示 NUnit 测试代码覆盖率
- azure - 长期运行的 Azure SQL 数据库维护
- java - 超类访问检查失败
- python - 有什么方法可以检测 Excel 工作簿是否在 Python 或 Robot 框架中受密码保护?
- python - 属性 Nonetype 没有方法 .count()
- performance - Is there a more efficient function for finding []byte similarities?
- javascript - 使用电子无法正常工作的网页