【发布时间】:2018-01-09 19:24:36
【问题描述】:
我正在开发一个使用 Ionic 3 和 Firebase 作为身份验证提供程序的混合应用程序。该应用程序包含 2 个页面。一个登录页面和一个主页。在登录页面上有一个使用电子邮件+密码登录用户的按钮,在主页上有另一个按钮注销当前用户。基本上,第一次加载应用程序时一切正常。但是在登录然后注销然后再次登录之后,onAuthStateChange 内部的函数被调用两次,然后是 3 次,然后是 5 次,依此类推,遵循斐波那契数列。 这是登录页面代码:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log('User logged-in');
if (user.emailVerified) {
self.goToHome();
} else {
self.showAlert();
firebase.auth().signOut();
}
}
});
}
这是注销代码:
firebase.auth().onAuthStateChanged(function(user) {
if (user == null) {
console.log('User logged-out');
navCtrl.push(WelcomePage);
}
});
chrome 控制台显示此行为:
(图片末尾的错误是我的错,因为我使用了错误的密码)
按钮调用的函数(但我 99% 确定问题出在 onAuthStateChanged):
doLogin() {
console.log('Trying to log in...');
var email = this.account.email;
var password = this.account.password;
if (this.validateEmail(email) && password.length >= 8) {
loading.present();
firebase.auth().signInWithEmailAndPassword(email, password)
.then(function(data) {
loading.dismiss();
});
}
logout() {
firebase.auth().signOut();
}
函数 goToHome 将用户移动到主页:
goToHome() {
this.navCtrl.push(MainPage);
}
Ben 在他的评论中指出的解决方案:
1:从 onAuthStateChanged 中移动所有与 navController 相关的函数 2:使用setRoot代替pop()和push()
goToHome() {
this.navCtrl.setRoot(HomePage);
}
logout() {
firebase.auth().signOut();
this.navCtrl.setRoot(WelcomePage);
}
3) 为了解决如果用户没有注销时能够自动登录的问题,我检查了 如果 firebase.auth().currentuser 存在,但使用超时,因为 Firebase 需要一些时间才能正常运行:
setTimeout(function(){
var user = firebase.auth().currentUser;
if (user != null) {
self.goToHome();
}
}, 1500);
【问题讨论】:
-
请同时提及您的
component路由逻辑。这是做什么self.goToHome();?
标签: javascript angular firebase ionic-framework firebase-authentication