我遵循 Firebase 文档进行 Web 开发,并使用了user.updateProfile
方法将显示名称添加到用户的个人资料中。登录后,我使用了console.log(user)
它起作用了,但是当我打电话时updateProfile()
, 的价值user
一片空白。有什么解决办法吗?
这是相关代码:
var button = document.getElementById("profile-button");
var username = document.getElementById("username-Box").value;
var user = firebase.auth().currentUser;
auth.onAuthStateChanged(user =>{
console.log(user);
})
function updateProfile(){
if (user != null){
user.updateProfile({
displayName : username
}).then(user => {
console.log("Updated Successfully");
window.location.href="chatpage.html";
}).catch(err =>{
console.log(err);
window.alert(err);
});
}else if(user == null){
console.log("No user signed in");
}
}
你需要等待onAuthStateChanged
在分配之前触发user
变量,否则 Auth 对象可能处于中间状态。这是有记录的:
通过使用观察者,您可以确保在获取当前用户时 Auth 对象不处于中间状态(例如初始化)。当您使用signInWithRedirect时,onAuthStateChanged观察者会等到getRedirectResult解析后再触发。
您还可以使用 currentUser 属性获取当前登录的用户。如果用户未登录,当前用户为空:
值得明确指出的是user
变量你console.log
in onAuthStateChanged
不一样user
您中使用的变量updateProfile
方法。虽然用户可能“登录”时onAuthStateChanged
火灾,当您设置外部时,它们可能尚未登录user
多变的。这就是你的问题所在。
从您的代码中不清楚在哪里updateProfile
被称为,但是彼得·哈达德的回答可能是我要实施的解决方案。但是,请注意,使用该答案中提供的代码片段,您还需要更改您的updateProfile
方法来接受user
范围。另一种方法是分配user
里面的变量onAuthStateChanged
.
let user;
auth.onAuthStateChanged(u => user = u);
通过这种方法你的updateProfile
方法应该按原样工作。请记住,您可能会遇到竞争条件,具体取决于您调用的时间updateProfile
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)