这是我的代码,用于在基于Firebase的身份验证应用程序中检查用户的当前身份验证状态。我希望访问用户参数(user.uid、user.photoURL等)在用于其他操作的auth.onAuthStateChanged函数之外,我无法这样做,因为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");
    }
});发布于 2020-12-05 23:08:03
正如在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。请注意,使用观察者很可能更容易。
https://stackoverflow.com/questions/65157394
复制相似问题