【发布时间】:2018-09-22 01:13:57
【问题描述】:
我是 AngularFire 和 Ionic 的新手。我跟着 this tutorial 将 Firebase Auth 添加到我的 ionic 项目中。
HomePage 是根页面。它检查 authState 以确定用户是否已登录。如果没有,它会重定向到 LoginPage。成功登录后,它再次将 HomePage 设置为 root。它没有按预期工作。
以下是控制台的日志:
Not logged in. Navigating to login page.
login.ts:27 ionViewDidLoad LoginPage
home.ts:22 User logged in. UID: taiNC6n64BP4gD8jTcnXUu53npc2
home.ts:22 User logged in. UID: taiNC6n64BP4gD8jTcnXUu53npc2
2home.ts:27 Not logged in. Navigating to login page.
login.ts:27 ionViewDidLoad LoginPage
login.ts:27 ionViewDidLoad LoginPage
首页相关代码:
constructor(private afAuth: AngularFireAuth, public navCtrl: NavController, public navParams: NavParams) {
this.afAuth.authState.subscribe(res => {
if (res && res.uid) {
console.log("User logged in. UID: " + res.uid);
//Do nothing
} else {
//Push them to the login page
console.log("Not logged in. Navigating to login page.");
this.navCtrl.setRoot('LoginPage');
}
});
}
登录页面代码:
async login(user: User){
try {
const result = await this.afAuth.auth.signInWithEmailAndPassword(user.email, user.password);
if (result) {
this.navCtrl.setRoot('HomePage');
}
}
catch (e) {
console.error(e);
}
}
从日志中可以看出,它正确显示用户在初始加载时已从应用程序中注销并重定向到登录页面。然后主页被重置为根。 authStat.subscribe 被击中 4 次。并且第二次用户不再可用。是什么导致了这种情况,我怎样才能使登录持久化?根据 AngularFire 文档,默认行为是持久登录。
--更新--
我尝试了以下解决方案。现在我的日志如下所示:
ionViewDidLoad HomePage
app.component.ts:26 Not logged in.
login.ts:27 ionViewDidLoad LoginPage
app.component.ts:23 Logged in.
home.ts:24 ionViewDidLoad HomePage
home.ts:24 ionViewDidLoad HomePage
app.component.ts:26 Not logged in.
login.ts:27 ionViewDidLoad LoginPage
以及我的 app.component.ts 文件中的代码:
export class MyApp {
@ViewChild(Nav) nav: Nav;
rootPage:any = 'HomePage';
constructor(private afAuth: AngularFireAuth, platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
this.afAuth.auth.onAuthStateChanged(user => {
if (user){
console.log("Logged in.");
this.nav.setRoot('HomePage');
} else {
console.log("Not logged in.");
this.nav.setRoot('LoginPage');
}
});
});
}
}
【问题讨论】:
标签: ionic-framework angularfire2