camstar915
camstar915

Reputation: 153

Angular Firebase ngIf user is authenticated listener doesn't work on page reload

I'm using onAuthStateChanged from firebase to listen to the authentication status of a user. I'm listening to those changes in my navigation component to decide whether to show a login button or a logout button etc..

This works fine if I'm navigating within the app, but when I refresh the page, the DOM reflect the state of the user even though the subscription gets fired.

Probably a simple fix that I'm overlooking, but I haven't been able to find a fix that works in my research and have put too much time into it -_- please help!

This is my authService:

  private authStatusSub = new Subject();
  user$ = this.authStatusSub.asObservable();

  setAuthStatusListener() {
    this.auth.onAuthStateChanged((user) => {
      if (user) {
        this.usersService
          .getUserData(user.uid)
          .then((userData) => {
            this.authStatusSub.next(userData);
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        this.authStatusSub.next(null);
        console.log('User has logged out');
      }
    });
  }

Navigation typescript file:

  isAuthenticated: boolean;

  ngOnInit() {
    this.authService.setAuthStatusListener();
    this.authService.user$.subscribe((userData) => {
      if (userData) {
        this.isAuthenticated = true;
        console.log(userData);
      } else {
        this.isAuthenticated = false;
      }
    });
  }

Navigation html:

  <a routerLink="/login" *ngIf="!isAuthenticated" mat-button class="navButton">Login</a>
  <a mat-button *ngIf="isAuthenticated" class="navButton" (click)="onLogout()">Logout</a>

When I go through the normal app flow and login, logout, and navigate to the home page (where the nav bar sits), it works as expected, but when I refresh the home page (where the nav bar sits), the state isn't reflected in the DOM. Even though the state isn't reflected, the console.log() in the nav typescript file is fired with the correct data, so I know the observable is working.

Would deeply appreciate any help!!!

Upvotes: 2

Views: 469

Answers (1)

BizzyBob
BizzyBob

Reputation: 14740

Since you are using AngularFireAuth, you can simplify your service like this:

Service:

  • get rid of Subject (authStatusSub)
  • define user$ directly from AngularFireAuth.authState
  • don't subscribe in service!

So the code could look like this:

service:

constructor(private fireAuth: AngularFireAuth) { }

user$ = this.fireAuth.authState;

nav component:

this.authService.user$.subscribe(
    userData => this.isAuthenticated = !!userData
);

Upvotes: 3

Related Questions