简体   繁体   中英

angular2-jwt token is not working, LoggedIn function not working

I am making a simple mean auth app, where angular2-jwt is used to authenticate the user logging in, right now, i want that before logging in, i dont want Dashboard, Profile to be shown on navbar, whereas after login, Register and Login should be hidden so i angular2-jwt, but it is not working correctly, i am sharing the code below. want to hide Dashboard, Profile before logging in

This is the code of navbar i am using

      <ul class="nav navbar-nav navbar-right">
    <li *ngIf="authService.loggedIn()" [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
      <a [routerLink]="['/dashboard']">Dashboard</a>
    </li>
    <li *ngIf="!authService.loggedIn()" [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
      <a [routerLink]="['/profile']">Profile</a>
    </li>
    <li *ngIf="!authService.loggedIn()" [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
      <a [routerLink]="['/login']">Login</a>
    </li>
    <li *ngIf="authService.loggedIn()" [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
      <a [routerLink]="['/register']">Register</a>
    </li>
    <li>
      <a *ngIf="authService.loggedIn()" (click)="onLogoutClick()" href="#">Logout</a>
    </li>
  </ul>

this is the service that i made

     loggedIn(){
return tokenNotExpired();

}

but upon using it, it hides Dashboard, Profile and Logout initially, but even after logging in, these three links are hidden, and not showing:

still not showing, even i am logged in

I am using this guide: https://github.com/auth0/angular2-jwt#checking-authentication-to-hideshow-elements-and-handle-routing

The problem here is since your tokenNotExpired returns a token you cannot use ngIf Directly over the funciton since it works over a boolean value, change your function as follows,

loggedIn(){
  if(tokenNotExpired() != null){
    return true;
  }
  return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM