Itika Bandta
Itika Bandta

Reputation: 163

Why does firebase.auth().currentUser return NULL even when the user is logged in

I am logging in my application using Firebase as below -

onSubmit(form){
this.authService.login(form.value.usermail, form.value.userpswd)
.then((data) => {
 this.router.navigateByUrl('/dashboard');

}).catch((error) => {
  this.errorMessage = error;
})

authService is -  login(email: string, password: string) {
                  return firebase.auth().signInWithEmailAndPassword(email, password)
                  }

I want to check if the user is logged in or out and on the basis of it set items/labels on my navigation bar accordingly. For example, the user will see LOGOUT label in the nav bar only if he is already logged in, etc.

HTML -

  <li class="nav-item" data-target=".navbar-collapse" data-toggle="collapse" 
   routerlinkactive="active"
   *ngIf="loggedIn">
    <a class="nav-link" (click)="logOut()">LOGOUT</a>
  </li>

The code on my navigation component is -

import { Component, OnInit } from '@angular/core';
import * as firebase from 'firebase/app';
import 'firebase/auth';
import { Router } from '@angular/router';
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit {

loggedIn : boolean = false;
user : any

constructor(private router: Router) {

this.user = firebase.auth().currentUser;

if(this.user){
  this.loggedIn = true;

} else {
  this.loggedIn = false;

}


firebase.auth().onAuthStateChanged((user)=>{
if(this.user){
  this.loggedIn = true;

} else {
  this.loggedIn = false;

}
console.log(firebase.auth().currentUser) 
console.log(firebase.auth()) 

}

ngOnInit() {
}

logOut(){

 console.log("LOGOUT")
 firebase.auth().signOut();
 this.router.navigateByUrl("/signup");

}
}

Even though firebase.auth() gives the correct data, firebase.auth().currentUser returns NULL because of which I am not able to set the value of loggedIn variable.

I have found many similar questions but have had no luck with any solution so far. Any help would be highly appreciated !!

Thanks in advance !!

Upvotes: 1

Views: 1564

Answers (1)

Nosheep
Nosheep

Reputation: 503

Avoid checking state with firebase.auth().currentUser, put the logic in the observer instead.

export class MenuComponent implements OnInit {

    loggedIn: boolean = false;

    constructor(private router: Router) {

        firebase.auth().onAuthStateChanged((user) => {
            if (user) {
                this.loggedIn = true;

            } else {
                this.loggedIn = false;
            }
        } 

        console.log("LOGOUT")
        firebase.auth().signOut();
        this.router.navigateByUrl("/signup");

    }
}

Upvotes: 1

Related Questions