1

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 !!

Tibebes. M
  • 6,940
  • 5
  • 15
  • 36
Itika Bandta
  • 163
  • 1
  • 2
  • 12
  • Why would you use both `onAuthStateChanged()` method and `currentUser` property? The recommended way is to use the `onAuthStateChanged()` method. – ruth Jun 07 '20 at 22:21
  • Does this answer your question? [Can't get currentUser on load](https://stackoverflow.com/questions/37883981/cant-get-currentuser-on-load) – ruth Jun 07 '20 at 22:26

1 Answers1

1

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");

    }
}
Santi Barbat
  • 2,097
  • 2
  • 21
  • 26
Nosheep
  • 493
  • 1
  • 4
  • 10
  • I tried that as well but it didn't work. Weird thing is that I can see the user inside firebase.auth() but not firebase.auth().currentUser – Itika Bandta Jun 08 '20 at 09:05
  • if user isn't signed in, firebase.auth().currentUser will return null regardless, it's intended. – Nosheep Jun 08 '20 at 09:25
  • within your observer solution replace this.user with user. – Nosheep Jun 08 '20 at 09:26
  • Thank you !!! It set the loggedIn value to true and solved what I was trying to achieve. But it still shows currentUser as NULL. What is the concept behind this? – Itika Bandta Jun 08 '20 at 09:36
  • I am not sure. Maybe it takes more time for that object to fully initialize, therefore it's null at the start. Nevertheless using Observer approach is a recommended way. – Nosheep Jun 08 '20 at 09:52