我正在尝试在登录后获取当前用户,但这返回null . 有我的代码:
var currentUser;
firebase
.auth()
.onAuthStateChanged(function(user){
currentUser = user;
console.log(currentUser); //this returns my user object
});
console.log(currentUser); //this returns "undefined"
var otherCurrentUser = firebase.auth().currentUser;
console.log(otherCurrentUser); // this returns "null"
2 回答
只要用户的身份验证状态发生更改,就会触发
onAuthStateChanged
事件 .user
变量仅在该回调中有用 . 您无法将其传输出该功能 .因此,需要用户的所有代码都应该在回调中:
有关这方面的更多信息,请参阅以下内容:
Using variable outside of ajax callback function
How do I return the response from an asynchronous call?
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
Firebase Query inside function returns null
这将返回null,因为auth对象尚未初始化,您需要一个观察者来执行此操作 . 登录时,使用观察者并将UID保存在localstorage中,并在注销时清除localstorage
观察
在此之后,只要您需要获取用户ID,只需使用即可
注销时只需将其删除即可
希望这可以帮助..!