Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular9 - check if Firebase user is currently logged in

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?

like image 266
methuselah Avatar asked Feb 01 '26 05:02

methuselah


1 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>
like image 179
ruth Avatar answered Feb 02 '26 20:02

ruth