Search code examples
angularfirebasefirebase-authenticationfirebaseui

Why am I obtaining this error trying to check if the user is logged in Firebase using AngularFireAuth?


I am working on an Angular application using AngularUI to handle user registration\login on Firebase (I am also using AngularFire2).

So I have this home component typescript code:

import { Component, NgZone, OnInit } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  constructor(public afAuth: AngularFireAuth,
              private router:Router,
              private ngZone: NgZone
             ) { }

  ngOnInit(): void {

    this.afAuth.authState.subscribe(this.firebaseAuthChangeListener);
  }
 
  
  private firebaseAuthChangeListener(response) {
 
    if (response) {
      console.log('Logged in :)');
      this.ngZone.run(() => this.router.navigate(['/home']));
     
    } else {
      console.log('Logged out :(');
    }
  }
}

And this is the view code of this component:

<div *ngIf="afAuth.currentUser">
    <h1>Logged in</h1>
</div>
<div *ngIf="!afAuth.currentUser">
    <h1>Logged out</h1>
    <firebase-ui></firebase-ui>
</div>

So as you can see in the view I am trying to use the afAuth.currentUser property to check if the user is logged in and to show the proper div related to the user status (if it is logged in or logged out).

The problem is that doing in this way it is not working. It take long time running trying to open my application (the browser's tab seems to be frezed because I can not open the console) and finnally it give me an error.

I am sure that FirebaseUI is correctly configured because if I put only this line into my home compoent html:

<firebase-ui></firebase-ui>

I correctly obtain the firebase ui log-in that I expect.

So the problem should be related on how I check if the user is logged in in this line:

<div *ngIf="afAuth.currentUser">

that uses AngularFireAuth class passed as dependency in the component constructor.

What is wrong? What am I missing? How can I correctly check if the user if logged in\out from my page?


Solution

  • For check user state You make us i recomend this article https://firebase.google.com/docs/auth/web/manage-users?authuser=0 I personally use this method for manage user state:

    afAuth.onAuthStateChanged(U => {
          if (U) {
            console.log('User loget in');
          } else {
            console.log('Log Out');
          }
        });