我正尝试使用以下代码在Ionic 2上使用firebase实现登录。
export class MyApp {
rootPage:any = Login;
isAuthenticated = false;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
firebase.initializeApp({
apiKey: "AIzaSyC94rD8wXG0aRLTcG29qVGw8CFfvCK7XVQ",
authDomain: "myfirstfirebaseproject-6da6c.firebaseapp.com",
});
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
this.rootPage = Home;
} else {
this.rootPage = Login;
}
});
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();
});
}
}
我意识到即使我经过身份验证,我也总是被带到登录界面,因为它不会等待onAuthStateChanged承诺得到满足并继续初始化应用程序,因此,登录屏幕而不是主屏幕是总是显示出来。
但是我应该如何更改我的代码,以便在验证时显示Home?
答案 0 :(得分:2)
从rootPage声明中删除登录
export class MyApp {
rootPage:any;
...
}
您可以在应用初始化时将页面设置为LoginPage,然后才能检查用户是否已暂停。
要运行onAuthStateChange
,当应用初始化时,您需要使用区域来创建一个可观察的并运行它。
import { NgZone } from '@angular/core';
zone: NgZone; // declare the zone
this.zone = new NgZone({});
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
this.zone.run(() => {
if (user) {
this.rootPage = Home;
unsubscribe();
} else {
this.rootPage = Login;
unsubscribe();
}
});
});
希望有所帮助