[英]AuthGuard: OnAuthStateChanged VS check token in Angular 5 + Firebase
Everytime an user signup , the following code is excetue:每次用户注册时,执行以下代码:
this.router.navigate(['/']);
firebase.auth().currentUser.getToken()
.then(
(token: string) => this.token = token
)
getToken method is so defined: getToken 方法是这样定义的:
getToken() {
firebase.auth().currentUser.getToken()
.then(
(token: string) => this.token = token
);
return this.token;
}
I save the Token because I have a Guard for the routing that checks if the user has the token:我保存令牌是因为我有一个用于检查用户是否拥有令牌的路由的Guard:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.authService.isAuthenticated();
}
Now, I just read in the documentation of Firebase that is a good practice to use onAuthStateChanged() to check if the user is signed in:现在,我刚刚阅读了 Firebase 的文档,这是使用onAuthStateChanged()检查用户是否登录的好方法:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
So, what is the best way to define if a (valid) user is signed in application with Angular + Firebase?那么,定义(有效)用户是否使用 Angular + Firebase 登录应用程序的最佳方法是什么?
I use this function to check if a user is logged in (using angularfire2, which is a lot of help because it provides you with wrappers in an Angular Way to the firebase js sdk https://github.com/angular/angularfire2 ):我使用此函数来检查用户是否已登录(使用 angularfire2,这很有帮助,因为它以 Angular 方式为您提供了 firebase js sdk https://github.com/angular/angularfire2 的包装器):
isLoggedIn(){
var promise = new Promise((resolve, reject) => {
this.afAuth.authState.subscribe(res => {
if (res && res.uid) {
console.log('user is logged in');
resolve(true);
} else {
console.log('user not logged in');
resolve(false);
}
});
});
return promise;
}
This is how you would use the function:这是您使用该功能的方式:
this.auth.isLoggedIn().then(
(val) => {
if(val){
//Do your re-direct
}else{
//send alert or something
}
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.