我正在使用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);
});
}
});