当前位置: 代码迷 >> JavaScript >> Firebase onAuthStateChanged()跳过代码
  详细解决方案

Firebase onAuthStateChanged()跳过代码

热度:44   发布时间:2023-06-07 16:33:12.0

我正在使用Firebase身份验证和Firestore开发应用程序注册功能。 目前,当我创建用户时,我还想在Firestore中创建一个文件。 但是,我的onAuthStateChanged()函数只是跳过了此操作。

 firebase.auth().onAuthStateChanged(function(user) { //User is signed in. if (user) { console.log("This happened."); //Create the Users document in the Firestore Database. firestore.collection("Users").doc(email).set({ UserEmail: email, UserRole: role }).then(function() { console.log("Document successfully written!"); }).catch(function(error) { console.error("Error writing document: " + error); }); console.log("This also happened."); //Redirect user to the dashboard for their role. if(role === "Customer") window.location.replace("customer.html"); else if (role === "Manager") window.location.replace("manager.html"); else if (role === "Deliverer") window.location.replace("deliverer.html"); else console.log("The value of role is not an accepted value: " + role + "."); } }); 

在浏览器中运行它,我看到了“这件事”。 和“这也发生了。” 控制台输出,而不会收到其他控制台输出或错误。 它还在if语句底部完成了重定向。 我在此文件以及其他文件中对该功能的使用一直感到烦恼,因此,非常感谢您的帮助! 谢谢!

任何需要用户登录状态的代码都必须在onAuthStateChanged回调内部。 您已经做完了,所以已经到了一半。

将数据成功写入数据库后必须运行的任何代码都必须在then()回调内部。 所以:

firebase.auth().onAuthStateChanged(function(user) {

    //User is signed in.
    if (user) {
        //Create the Users document in the Firestore Database.
        firestore.collection("Users").doc(email).set({
            UserEmail: email,
            UserRole: role
        }).then(function() {
            console.log("Document successfully written!");

            //Redirect user to the dashboard for their role.
            if(role === "Customer") window.location.replace("customer.html");
            else if (role === "Manager") window.location.replace("manager.html");
            else if (role === "Deliverer") window.location.replace("deliverer.html");
            else console.log("The value of role is not an accepted value: " + role + ".");
            else console.log("The value of role is not an accepted value: " + role + ".");
        }).catch(function(error) {
            console.error("Error writing document: " + error);
        });    
    }

});