我在Ionic 3中设置了一个简单的应用程序,其中包含登录页面和主页。我检查用户是否已登录,然后重定向到登录页面或主页。那部分似乎有效。
登录后,在主页上我试图获取当前登录用户。我得到用户两次,然后它返回两次null。为什么用户不坚持?根据AngularFire文档,默认情况下登录应该是持久的。
app.component.ts:
export class MyApp {
@ViewChild(Nav) nav: Nav;
rootPage:any;
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();
const authObserver = this.afAuth.authState.subscribe(user =>{
if (user){
this.rootPage = 'HomePage';
authObserver.unsubscribe();
} else {
this.rootPage = 'LoginPage'
authObserver.unsubscribe();
}
});
});
}
}
login.ts:
export class LoginPage {
user = {} as User;
constructor(public authData: AuthProvider, public navCtrl: NavController, public navParams: NavParams) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad LoginPage');
}
login(user: User){
this.authData.loginUser(user.email, user.password).then( authData => {
this.navCtrl.setRoot('HomePage');
}, error => {
console.log('Something went wrong')
});
}
}
home.ts:
export class HomePage {
constructor(private afAuth: AngularFireAuth, public authData: AuthProvider, public navCtrl: NavController, public navParams: NavParams) {
this.afAuth.auth.onAuthStateChanged(user => {
console.log(user);
});
}
}
日志:
login.ts:27 ionViewDidLoad LoginPage
home.ts:22 Hk {D: Array(0), G: "XIzaSyDn9pRx23NeEaCNVMQ0sBveDxYEsGrGvRA", s: "[DEFAULT]", A: "pigs-n-bulls-xxxxxxxx.firebaseapp.com", b: xh, …}
home.ts:22 Hk {D: Array(0), G: "XIzaSyDn9pRx23NeEaCNVMQ0sBveDxYEsGrGvRA", s: "[DEFAULT]", A: "pigs-n-bulls-xxxxxxxx.firebaseapp.com", b: xh, …}
home.ts:27 ionViewDidLoad HomePage
home.ts:22 null
home.ts:22 null
答案 0 :(得分:0)
this.afAuth.auth.auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL);
或
this.afAuth.auth.auth.setPersistence(firebase.auth.Auth.Persistence.SESSION);
然后在您的身份验证代码中:
this.afAuth.auth.auth.onAuthStateChanged(user => {
if (!user) {
}
}
请注意,我不是在使用Angularfire,而是直接访问Firebase身份验证功能。