What is the best way to check if the user is currently logged in on Angular 9? Initially, I would do it this way:
constructor(
public afAuth: AngularFireAuth,
private logger: NGXLogger
) {
this.afAuth.authState.subscribe((result) => {
if (result) {
this.user = result;
}
});
}
public isLoggedIn(): boolean {
const user = this.afAuth.currentUser;
return !!user;
}
And then call it from my component in this way:
isLoggedIn(): boolean {
return this.authService.isLoggedIn();
}
<button
*ngIf="!isLoggedIn()"
class="btn btn-glass btn-primary"
id="builder-header-create-account"
type="button"
>
Sign Up
</button>
But after upgrading to Angular 9, the above code causes my UI to hang. What is the best way of fixing it?
You could try to use the onAuthStateChanged() function. Try the following
Service
loggedIn = new BehaviorSubject<boolean>(false);
loggedIn$ = this.loggedIn.asObservable();
constructor(
public afAuth: AngularFireAuth,
private logger: NGXLogger
) {
this.afAuth.auth.onAuthStateChanged((user) => {
if (user) {
this.loggedIn.next(true);
} else {
// not logged in
this.loggedIn.next(false);
}
});
}
public isLoggedIn(): boolean {
return !!this.afAuth.currentUser;
}
Component
<button
*ngIf="!(authService.loggedIn$ | async)"
class="btn btn-glass btn-primary"
id="builder-header-create-account"
type="button"
>
Sign Up
</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With