Search code examples
angulartypescriptangular7behaviorsubjectangular-changedetection

enable Logout button only after Login in Angular 7


I have refered the below link for enabling the logout button only after login https://stackblitz.com/edit/angular-login-hide-navbar-ngif

I want to display the "logout" in navbar only when user is logged in for which I am verifying if the user is logged in by calling "this.authservice.isUserLoggedIn" from "Authenication service" and assigning it to a variable and writing a ngif condition near "logout" link. I have used BehaviourSubject to get the current state. But I don't know why the code is not working and it is always returning false and hence "logout" link is not enabled even after user is logged in

I have header.component.ts

export class CommonheaderComponent implements OnInit {

  constructor(private authservice : AuthenticationService) { }
  isLoggedIn$ : Observable<boolean>;
  ngOnInit() {
    this.isLoggedIn$ = this.authservice.isUserLoggedIn;
  }
  }

I have the header.component.html as below

<ul class="nav navbar-nav">
      <li><a [routerLink]='["/search"]'>Search <span class="slider"></span></a></li>
      <li *ngIf="isLoggedIn"><a (click)="logout()">Logout</a></li>
  </ul>

Below is the login.component.ts

export class LoginComponent implements OnInit {
  isLoggedIn : Observable<boolean>;

 ngOnInit() {
   this.isLoggedIn = this.authservice.isUserLoggedIn;
   this.loginForm = this.formbuilder.group({
    username : ['', Validators.required],
    password : ['', Validators.required]
  })
 }

}

  onSubmit(){
    this.authservice.login(this.loginForm.value).subscribe(data => {
  })    
 }
}

I have the authentication service as below

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { BehaviorSubject, Observable } from 'rxjs';
    import { map } from 'rxjs/operators';
    import { User } from '../_models/user';
    import { Router } from '@angular/router';

    const httpOptions =  {
      headers : new HttpHeaders({'Content-type' : 'application/json'})
    }

    @Injectable({
      providedIn: 'root'
    })
    export class AuthenticationService {
      private currentUserSubject : BehaviorSubject<User>;
      private currentUser : Observable<User>;
      private loggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

      constructor(private http: HttpClient, private router: Router) {
        this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
        this.currentUser = this.currentUserSubject.asObservable();
      }

      public get currentUserValue(): User{
        return this.currentUserSubject.value;
      }

      public login(user: User):Observable<any>{
        var baseUrl = "http://localhost:3000/";
        return this.http.post<any>(baseUrl+'auth/login', user, httpOptions).pipe(map(user => {
          if(user && user.accesstoken){
            localStorage.setItem('currentUser', JSON.stringify(user));
            this.currentUserSubject.next(user);
            this.loggedIn.next(true);
          }else{
            return false;
          }
          return user;
        }))
      }

      get isUserLoggedIn(){
          return this.loggedIn.asObservable();
      } 
    }

Where did I do the mistake. Or what is the solution / alternate for this. Please help!!

I am stuck with this since long time


Solution

  • Can you try after changing your template like this:

    <ul class="nav navbar-nav">
          <li><a [routerLink]='["/search"]'>Search <span class="slider"></span></a></li>
          <li *ngIf="isLoggedIn$ | async"><a (click)="logout()">Logout</a></li>
      </ul>
    

    Notice the async pipe to unwrap the observable value.

    Notice in the stackblitz example shared by you - Observable value was unwrapped using async pipe -

    <mat-toolbar color="primary" *ngIf="isLoggedIn$ | async as isLoggedIn">