即使用户已登录,Firebase javascript auth 用户也显示 null

2023-12-13

我遵循 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(使用前将#替换为@)

即使用户已登录,Firebase javascript auth 用户也显示 null 的相关文章

随机推荐