【问题标题】:Angular 4/5 Firebase Current User in Console disappears on refresh控制台中的 Angular 4/5 Firebase 当前用户在刷新时消失
【发布时间】:2018-01-17 04:21:50
【问题描述】:

我使用 Firebase 构建了一个 Angular 5 Login,并通过以下方式在控制台中记录了当前用户。 它工作正常,在通过路由加载另一个页面时也是如此。但是当我重新加载页面时,auth 对象消失了 - 但用户保持登录状态(home component.html 中的用户名,例如保持显示)

登录组件.ts

  onLoginEmail(): void {
if (this.validateForm(this.email, this.password)) {
  this.authService.loginWithEmail(this.email, this.password)
    .then(() => this.router.navigate(['/home']))
    .catch(_error => {
      this.error = _error
      this.router.navigate(['/'])
    })
}

}

auth.service.ts

  loginWithEmail(email: string, password: string) {
return this.afAuth.auth.signInWithEmailAndPassword(email, password)
  .then((user) => {
    this.authState = user
    this.isLoggedIn()
  })
  .catch(error => {
    console.log(error)
    throw error
  });

}

isLoggedIn() {
    this.afAuth.auth.onAuthStateChanged(auth => {
      if (auth) {
        console.log(auth);
      } else {
        console.log('User logged out');
      }
    });
  }

(这是一种常见的方法吗?有更好的方法吗?)

【问题讨论】:

    标签: angular firebase firebase-authentication angular5


    【解决方案1】:

    身份验证状态将是持久的,因此您刷新页面并且同一用户仍处于登录状态是正常的。听起来您的问题是,当您刷新页面时,无论代码将用户打印到控制台没有被调用。函数 isLoggedIn 不应该从 signInWithEmailAndPassword() 返回的 promise 内部调用,这真的没有意义。如果 signInWithEmailAndPassword() 成功,onAuthStateChanged 将发出一个新值,因此您应该在尝试登录用户之前调用 isLoggedIn()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      • 1970-01-01
      • 2020-03-10
      • 2019-03-12
      • 2020-02-04
      相关资源
      最近更新 更多