【问题标题】:After refresh, firebase Auth current user returns null刷新后,firebase Auth当前用户返回null
【发布时间】:2020-02-04 07:34:34
【问题描述】:

这是我在个人资料页面上的代码,当我从 AuthService 的登录方法重定向时,这第一次运行良好

const user = firebase.auth().currentUser;
  if (user != null) {
    this.name = user.displayName;
    this.uid = user.uid;
  } else {
    this.name = "Unknown";
  }

但是,如果我刷新页面或转到任何其他页面并返回此个人资料页面,currentUser 将变为 null。

这是我的身份验证服务代码。

import * as firebase from "firebase/app";
import { auth } from "firebase/app";

      async googleSignin() {
    firebase
      .auth()
      .setPersistence(firebase.auth.Auth.Persistence.LOCAL)
      .then(async () => {
        const provider = new auth.GoogleAuthProvider();
        const credential = await this.afAuth.auth.signInWithPopup(provider);
        this.updateUserData(credential.user);
        this.router.navigate(["/profile"]);
        return;
      });
  }

为什么我失去了 currentUser?我什至还添加了 Persistence.LOCAL。

【问题讨论】:

    标签: javascript angular firebase firebase-authentication


    【解决方案1】:

    当您导航到新页面时,您正在重新加载 Firebase 身份验证 SDK。此时 Firebase 会自动刷新当前用户的身份验证状态,但这可能需要往返服务器。当你的`firebase.auth().currentUser 运行时,刷新显然还没有完成。

    因此,您应该使用onAuthStateChange 来监听更改,如getting the currently signed in user 上的文档所示:

    firebase.auth().onAuthStateChanged(function(user) {
      if (user != null) {
        this.name = user.displayName;
        this.uid = user.uid;
      } else {
        this.name = "Unknown";
      }
    });
    

    【讨论】:

    • 谢谢弗兰克。问题是导航到站点的其他页面如何改变身份验证?这会在几秒钟内发生。我错过了什么?
    • 我不确定我是否理解。你能改写一下吗?
    • 我的应用中有三个页面,登录、个人资料和主页。登录页面,登录用户。登录后,我被重定向到个人资料页面。在个人资料页面 ''' const user = firebase.auth().currentUser;上面的代码有效!但是,如果我导航回主页甚至刷新个人资料页面,同一行代码给我的用户 null。我的问题是我们在哪里失去了用户?
    • 加载新页面时,会重新加载 Firebase 身份验证。它会自动刷新当前用户的身份验证状态,但这可能需要往返服务器。当您的firebase.auth().currentUser 运行时,刷新尚未完成,而我的onAuthStateChanged 代码保证在用户令牌刷新后执行您的代码。
    【解决方案2】:

    您还可以将用户数据保存到本地/会话存储中,以防服务/防护由于异步操作而无法及时接收。

    【讨论】:

    • 当然可以。但更大的问题是为什么 Auth 状态会发生变化?为什么页面刷新会丢失当前用户?
    • 因为它是后台的服务器调用,它是异步操作,它返回一个承诺,所以你有 ti promise.then() 等待数据到达或使用异步/等待
    • 我的应用中有三个页面,登录、个人资料和主页。登录页面,登录用户。登录后,我被重定向到个人资料页面。在个人资料页面 const user = firebase.auth().currentUser;上面的代码有效!但是,如果我导航回主页甚至刷新个人资料页面,同一行代码给我的用户 null。我的问题是我们在哪里失去了用户?
    猜你喜欢
    • 1970-01-01
    • 2022-01-16
    • 2019-08-05
    • 1970-01-01
    • 2019-04-12
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    相关资源
    最近更新 更多