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() {
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:
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.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?
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 ):
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
}
}
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.