title: Angular Firebase auth, how to check if user is logged in to hide login link from navigation?
body: <p>I implemented angular firebase email and password registration and login, but now what I want to do is check in my navigation template the state of the user, if the user is logged in, then hide login button, as well as hide register button. I tried googling for some tutorials on this, and found out that I must use AuthService and AuthInfo as you can see here:</p>
  
  <p><a href="https://github.com/angular-university/angular-firebase-app/blob/master/src/app/shared/security/auth.service.ts" rel="nofollow noreferrer">https://github.com/angular-university/angular-firebase-app/blob/master/src/app/shared/security/auth.service.ts</a></p>
  
  <p>The thing is that they are using a lot of promises and stuff, which I'm not familiar with and it really confuses me. I'm trying to achieve this in the most basic way and looking for someone to guide me and help me.</p>
  
  <p>Here is my code now:</p>
  
  <p><strong><em>navigation -</em></strong></p>
  
  <pre><code>&lt;ul class="nav navbar-nav"&gt;
      &lt;li&gt;&lt;a routerLink="" routerLinkActive="active"&gt;Home&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a routerLink="login" routerLinkActive="active" *ngIf="!authInfo?.isLoggedIn()"&gt;Login&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a routerLink="register" routerLinkActive="active" *ngIf="!authInfo?.isLoggedIn()"&gt;Register&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a routerLink="quiz" routerLinkActive="active"&gt;Quiz&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;
  </code></pre>
  
  <p>My <strong><em>Auth service</em></strong> file with all the user create and login to firebase logic -</p>
  
  <pre><code>@Injectable({
      providedIn: 'root'
  })
  export class AuthService {
      private user: Observable&lt;firebase.User&gt;;
      constructor(private _firebaseAuth: AngularFireAuth, private router: Router) {
          this.user = _firebaseAuth.authState;
  
          this.user.subscribe(
              (user) =&gt; {
                  if (user) {
                      this.userDetails = user;
  
                      console.log(this.userDetails);
                  } else {
                      this.userDetails = null;
                  }
              }
          );
      }
  
      logUserIn(email, pass) {
          firebase.auth().signInWithEmailAndPassword(email, pass).catch(function (error) {
              // Handle Errors here.
              var errorCode = error.code;
              var errorMessage = error.message;
              console.log("error" + error);
          })
  
          if (this.userDetails) {
              email = this.userDetails.email;
              console.log("hello im user" + " " + email);
  
          } else {
              console.log("not working");
          }
  
          this.router.navigate(['']);
      }
  
      regUser(email, pass) {
          firebase.auth().createUserWithEmailAndPassword(email, pass)
              .catch(function (error) {
                  // Handle Errors here.
                  var errorCode = error.code;
                  var errorMessage = error.message;
  
              });
      }
  }
  </code></pre>
  
  <p><strong><em>Login component -</em></strong> </p>
  
  <pre><code>@Component({
      selector: 'login',
      templateUrl: 'login.component.html'
  })
  export class LoginComponent {
  
      form: FormGroup;
  
      constructor(fb: FormBuilder, private _loginService: LoginService, private auth: AuthService) {
  
          this.form = fb.group({
              email: ['', Validators.required],
              password: ['', Validators.compose([Validators.required,
              PasswordValidator.cannotContainSpace])]
          })
  
      }
  
      login() {
          this.auth.logUserIn(this.form.value.email, this.form.value.password);
      };
  }
  </code></pre>
  
  <p><strong><em>auth-info.ts</em></strong> file from the github link above -</p>
  
  <pre><code>export class AuthInfo {
  
      constructor(public $uid: string) { }
  
      isLoggedIn() {
          return !!this.$uid;
      }
  }
  </code></pre>
  
  <p><strong><em>EDIT:</em></strong></p>
  
  <p>So thanks to Tushar Walzade I managed to show and hide these buttons, but I get really weird behaviour. There are no problems when logging out, but when I login, nothing happens, I get <code>not working</code> message to Chrome console which comes from my <code>logUserIn</code> method in Auth service. But when I refresh page one time, then it shows me that it's working, I get user information details in console and buttons get hidden. I don't know why this happens, but I think this might be something with <code>sessionStorage</code> which I know nothing about.</p>
  
  <p>Here is the code:</p>
  
  <p><strong><em>Auth service</em></strong></p>
  
  <pre><code>export class AuthService {
    private user: Observable&lt;firebase.User&gt;;
    private userDetails: firebase.User = null;
    public loggedIn = false;
  
  
  
    constructor(private _firebaseAuth: AngularFireAuth, private router: Router) {
      this.user = _firebaseAuth.authState;
      this.loggedIn = !!sessionStorage.getItem('user');
  
      this.user.subscribe(
          (user) =&gt; {
            if (user) {
              this.userDetails = user;
  
              console.log(this.userDetails);
            } else {
              this.userDetails = null;
            }
          }
        );
    }
  
    // Set current user in your session after a successful login
      setCurrentUser(email: string): void {
          sessionStorage.setItem('user', email);
          this.loggedIn = true;
      }
  
      // Get currently logged in user from session
      getCurrentUser(): string | any {
          return sessionStorage.getItem('user') || undefined;
      }
  
      isLoggedIn() {
      return this.loggedIn;
      }
  
    logUserIn(email, pass) {
      firebase.auth().signInWithEmailAndPassword(email, pass).catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  console.log("error" + error);
  })
  //var user = firebase.auth().currentUser;
  //var email;
  if (this.userDetails) {
  email = this.userDetails.email;
  console.log("hello im user" + " " + email);
  //email = user.email;
  this.setCurrentUser(email);
   this.loggedIn = true;
  } else {
  console.log("not working");
  }
  
  this.router.navigate(['']);
  }
  
    regUser(email, pass) {
      firebase.auth().createUserWithEmailAndPassword(email, pass)
   .catch(function(error) {
     // Handle Errors here.
     var errorCode = error.code;
     var errorMessage = error.message;
     // ...
   });
  //console.log(this.form.controls['email'].value);
      }
  
      logOut() {
        this.loggedIn = false;
        firebase.auth().signOut().then(function() {
          // Sign-out successful.
          console.log("signout successful");
      }).catch(function(error) {
          // An error happened.
          console.log("error happened");
        });
      }
  
    }
  </code></pre>
  
  <p><strong><em>Login component</em></strong></p>
  
  <p>export class LoginComponent  {</p>
  
  <pre><code>form: FormGroup;
  
  constructor(fb: FormBuilder, private _loginService: LoginService, private auth: AuthService){
  
      this.form = fb.group({
          email:['',Validators.required ],
    password:['',Validators.compose([Validators.required,
  </code></pre>
  
  <p>PasswordValidator.cannotContainSpace])]
          })</p>
  
  <pre><code>}
  
  login(){
        this.auth.logUserIn(this.form.value.email, this.form.value.password);
  </code></pre>
  
  <p>};</p>
  
  <p>}</p>
  
  <p><strong>app.component.ts</strong> because I have my router outlet and links in <strong><em>app.component.html</em></strong></p>
  
  <pre><code>export class AppComponent {
  
    title = 'angular-draganddrop';
    constructor(private auth: AuthService) { }
    LoggedIn() {
        return this.auth.isLoggedIn();
    }
    logout() {
      return this.auth.logOut();
    }
  }
  </code></pre>
  
  <p><strong><em>EDIT EDIT:</em></strong></p>
  
  <p>So I checked application session storage in Chrome and when I log out I indeed see my user email still there. I have to delete it by hand. Then when trying to log in first time it doesn't work and there is also no user email in session storage. Second time it gets added. The login system was working fine until adding sessionStorage functionality to code so it's definitely related to it. I don't know how sessionStorage works so I'm looking for a help to solve this.</p>