我正在使用firebase进行登录和注册。 那是我的authService样子:
token: string;
authenticated: boolean = false;
signinUser(email: string, password: string) {
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then(response => {
this.authenticated = true;
console.log('authService-->signinUser-->authenticated', this.authenticated);
//Set the a wallet using a combination of the email and the name of the network e.g. Majd@gmail.com@stschain
this.dataService.setWallet(`${email}${this.domainExtenstion}`);
this.setEmail(email);
this.router.navigate(['/dashboard']);
console.log('sinign in')
firebase
.auth()
.currentUser.getIdToken()
.then(
(token: string) => {
(this.token = token);
// localStorage.setItem('token', JSON.stringify(token));
}
);
})
.catch(error => {
console.log(error);
alert(error);
});
}
isAuthenticated() {
return this.token != null;
}
并且在我的authGuardService中,即时消息调用可以激活这样的方法:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (!this.authService.authenticated) {
console.log('cant load' )
this.router.navigate(['/signin']);
}
console.log('can load' )
return this.authService.isAuthenticated();
}
}
但是当我刷新页面时,此authenticated
值始终为false。
任何人,请知道会感激的原因。
答案 0 :(得分:0)
在您的代码中,您可以这样做:
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then(response => {
this.authenticated = true;
此then
块仅在用户显式登录时运行。重新加载页面后,它不会自动运行。
但是Firebase身份验证会在页面重新加载时自动(尝试)恢复用户的登录会话,您的代码只是不知道它。要检测身份验证状态更改,请使用身份验证状态侦听器(如documentation中所示):
firebase.auth().onAuthStateChanged(function(user) { if (user) { // User is signed in. } else { // No user is signed in. } });
请注意,onAuthStateChanged
回调会同时针对显式(例如,您调用signInWith...
)和隐式(例如,页面重新加载)身份验证状态更改进行调用,因此请考虑从{中移出(部分)代码{1}}阻止此回调。