![](/img/trans.png)
[英]How does this Firebase onAuthStateChanged work in this code
[英]Firebase onAuthStateChanged() skipping code
我正在使用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);
});
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.