【问题标题】:How do I access user parameters outside auth.onAuthStateChanged?如何访问 auth.onAuthStateChanged 之外的用户参数?
【发布时间】:2020-12-05 13:27:42
【问题描述】:

这是我在基于 Firebase 的身份验证应用程序中检查用户当前身份验证状态的代码。我希望访问auth.onAuthStateChanged 函数之外的用户参数(user.uid、user.photoURL 等)以将其用于其他操作,但我无法这样做,因为var user = firebase.auth().currentUser; 和其他类似方法正在返回null,因为因为 Firebase-Auth 不加载。我将不胜感激。

const auth = firebase.auth();

auth.onAuthStateChanged(function(user) {
    if (user) {
        authState = true;
        createUser(user.uid, user.displayName, user.photoURL);
        console.log("Current state: Logged in, User ID: " + user.uid);
    } else {
        authState = false;
        console.log("Current state: Logged out");
    }
});

【问题讨论】:

  • 不清楚你是如何尝试访问firebase.auth().currentUser的,记住这是一个同步访问,在用户登录之前会返回null之后会返回一个用户 他们进行了身份验证(即在 onAuthStateChanged 被新用户触发之后)。如果你想访问currentUser,你需要确保它在用户登录后被访问。你有例子吗?

标签: javascript firebase firebase-authentication


【解决方案1】:

正如doc 中所述,通过使用onAuthStateChanged() 设置观察者,您“确保在获取当前用户时 Auth 对象不处于中间状态(例如初始化)”。

因此,您应该在传递给onAuthStateChanged() 的回调函数中更新任何变量或任何DOM tree 节点,或调用任何使用user 值的函数,如文档所示:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
    // Here call any function which uses the user value, as follow
    displayUserName(user);

    // OR
    // Set any variable or DOM element with the user value
  } else {
    // No user is signed in.
  }
});

function displayUserName(user) {
   // ....
}

如果您不想对观察者使用上述方法,则可以使用currentUser 属性,但同样,它“也可能是null,因为auth 对象尚未完成初始化”。因此,当它是null 时由您来处理,然后重试直到它不是null。请注意,使用观察者可能更容易。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多