Angular9 - check if Firebase user is currently logged in

Viewed 1326

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?

3 Answers

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>

The official github has a small section on this: https://github.com/angular/angularfire/blob/master/docs/auth/getting-started.md

All you need to do is...

myPage.component.ts

import { AngularFireAuth } from '@angular/fire/auth';
//...
constructor(public afAuth: AngularFireAuth) { }

myPage.component.html

<div *ngIf="(afAuth.user | async)">User is logged IN</div>
<div *ngIf="!(afAuth.user | async)">User is logged OUT</div>

What works for me and keeps the system from clogging up is if I just take the first event in the observer.

this.angularFireAuth.authState.pipe(first()).subscribe(
  user => {
    this.isLoggedIn = !!user;
  }
);
Related