我试图用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();
});
}
}
我意识到,即使我经过身份验证,我也总是被带到登录屏幕上总是显示。
但是我应该如何更改代码,以便在身份验证时可以显示回家?
从rootpage声明中删除登录
export class MyApp {
rootPage:any;
...
}
您是在应用程序初始化时将页面设置为登录页,并且在他可以检查用户是否挂起之前。
让它运行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();
}
});
});
希望它有帮助