![](/img/trans.png)
[英]Firebase onAuthStateChanged always returning undefined
[英]Firebase OnAuthStateChanged function not returning anything
我在login.html
使用Firebase基於密碼的身份驗證。 我有2個文本框和3個按鈕。
我使用firebase.OnAuthStateChanged
來了解用戶是否已登錄或注銷。 當用戶登錄時,密碼文本框和登錄按鈕應該被隱藏,所以我使用display : none;
為了它。 當用戶注銷時,應該隱藏注銷按鈕。
按鈕工作正常,但真正的問題是在if elseif
語句中。
以下是我的JavaScript代碼。
PS:隨意使用Firebase配置進行測試。 或者使用此登錄信息:
// Initialize Firebase
var config = {
apiKey: "AIzaSyDjYqNKbZaom0jplOusloWlr5mOhW2WbgQ",
authDomain: "awes-e3043.firebaseapp.com",
databaseURL: "https://awes-e3043.firebaseio.com",
storageBucket: "awes-e3043.appspot.com",
messagingSenderId: "191054424051"
};
firebase.initializeApp(config);
// SignIn
$("button#in").click(function(){
var email = document.getElementById('logemail');
var password = document.getElementById('logpassword');
firebase.auth().signInWithEmailAndPassword(email.value, password.value).catch(function(error) {
console.log(error.code);
console.log(error.message);
}).then(function(){
location.reload();
});
});
// SignOut
$("button#out").click(function(){
firebase.auth().signOut().then(function() {
console.log("Logged out!")
location.reload();
}, function(error) {
console.log(error.code);
console.log(error.message);
});
});
$(document).ready(function(){
function usigned(){
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
return true;
} else {
return false;
}
}); }
if (usigned() == true) {
$("#hlogp").css("display", "none");
$("button#in").css("display", "none");
$("button#out").css("display", "inline-block")
}else if(usigned() == false) {
$("button#out").css("display", "none");
$("#hlogp").css("display", "block");
$("button#in").css("display", "block");
}
});
與大多數firebase調用一樣,onAuthStateChanged()以異步方式運行,因此您需要使用回調進行設置:
function usigned(bool) {
if (bool) {
$("#hlogp").css("display", "none");
$("button#in").css("display", "none");
$("button#out").css("display", "inline-block");
} else {
$("button#out").css("display", "none");
$("#hlogp").css("display", "block");
$("button#in").css("display", "block");
}
}
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
usigned(true);
} else {
usigned(false);
}
});
或者,您可以簡單地將usigned()代碼放入內聯...
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
$("#hlogp").css("display", "none");
$("button#in").css("display", "none");
$("button#out").css("display", "inline-block")
} else {
$("button#out").css("display", "none");
$("#hlogp").css("display", "block");
$("button#in").css("display", "block");
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.