Reputation: 99
I built an Angular 5 Login with Firebase and logged the current User in the console the following way. It works fine, also when loading another page via routes. But when I reload the page, the auth object disappears - but the user stays logged in (username in home component.html eg stays displayed)
Login Component.ts
onLoginEmail(): void {
if (this.validateForm(this.email, this.password)) {
this.authService.loginWithEmail(this.email, this.password)
.then(() => this.router.navigate(['/home']))
.catch(_error => {
this.error = _error
this.router.navigate(['/'])
})
}
}
auth.service.ts
loginWithEmail(email: string, password: string) {
return this.afAuth.auth.signInWithEmailAndPassword(email, password)
.then((user) => {
this.authState = user
this.isLoggedIn()
})
.catch(error => {
console.log(error)
throw error
});
}
isLoggedIn() {
this.afAuth.auth.onAuthStateChanged(auth => {
if (auth) {
console.log(auth);
} else {
console.log('User logged out');
}
});
}
(Is this a common way to do so? Are there better ways?)
Upvotes: 0
Views: 270
Reputation: 146
The auth state will be persistent, so it's normal for you to refresh the page and the same user to still be logged in. It sounds like your issue is that when you refresh the page, whatever code is printing the user to the console is not being called. The function, isLoggedIn, shouldn't be called from inside the promise returned by signInWithEmailAndPassword(), that just doesn't really make sense. If signInWithEmailAndPassword() is successful, onAuthStateChanged will emit a new value, so you should call isLoggedIn() even before you try to log the user in.
Upvotes: 1