In the code below you can see that I try to save a firebase token in local storage after login, which also works fine. The problem is that navigation runs before the token is set in local storage, and the user therefore has to press the login button twice.
Why this is happening? how can I fix it? This is the relevant code:
public signIn(email: string, password: string): Promise<User> {
console.log('Signing in as: ', email);
this.userData = this.auth.signInWithEmailAndPassword(email, password)
.then( credential => credential.user );
this.setToken();
if (!this.isAuthenticated()) {
console.log('not authenticated');
this.router.navigate(['']);
}
this.router.navigate(['/dashboard']);
return this.userData;
}
setToken() {
// this.afAuth.auth.currentUser.getIdToken(true).then((token) => localStorage.setItem('tokenId', token));
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
firebase.auth().currentUser.getIdToken().then((token) => localStorage.setItem('tokenId', token));
console.log('set token succes');
} else {
console.log('set token failed');
}
});
}
getToken() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
firebase.auth().currentUser.getIdToken().then((token) => localStorage.getItem('tokenId'));
// return this.currentTokenInlocal;
console.log('get token succes');
} else {
console.log('get token failed');
}
});
}