首页 > 解决方案 > 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 () {
}, 

请让我知道解决此问题的“角度方式”/最佳方式是什么。

标签: javascripthtmlangular

解决方案


你所做的是一个很好的解决方法,但你应该实际使用的是life cycle hook(s)例如: ngAfterViewInit

ngAfterViewInit() {
   this.isLoggedIn();
}

推荐阅读