angular - 刷新页面以角度 5 自动注销
问题描述
我正在使用 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 方法,如下所示:
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
值总是假的。
请任何人都知道会感激的原因。
解决方案
在您的代码中,您可以:
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then(response => {
this.authenticated = true;
此then
块仅在用户显式登录时运行。它不会在页面重新加载时自动运行。
但是当页面重新加载时,Firebase 身份验证会自动(尝试)恢复用户的登录会话,您的代码只是不知道它。要检测身份验证状态更改,请使用身份验证状态侦听器(如文档中所示):
firebase.auth().onAuthStateChanged(function(user) { if (user) { // User is signed in. } else { // No user is signed in. } });
请注意,onAuthStateChanged
显式(例如您调用signInWith...
)和隐式(例如页面重新加载)身份验证状态更改都会调用回调,因此请考虑将(部分)代码从then()
块移动到此回调。
推荐阅读
- ios - UITextField 编辑时自定义背景颜色
- azure - QnA Maker 知识库未显示
- javascript - Vue.JS、Axios、CanvasJS - 从 API 获取数据并填充/渲染图表
- c++ - 错误与
在 C++、Windows 中使用库时 - sql-server - VM 和主机之间的 SQL 链接服务器配置
- sharepoint-online - SharePoint SPFX(无框架)如何从 onclick 调用函数
- architecture - 具有 API 网关和微服务的 Blazor 服务器指南
- java - 使用 getResourceAsStream() 从子包访问资源文件夹
- flutter - Getter 方法返回空值
- html - 使用 Jsoup 获取 iframe src 链接