Eddie
Eddie

Reputation: 1228

Angular 2: Change element based on authenticated property

I've got an Angular 2 app that I have integrated authentication into using a service. The user can login, and when there is a token in the localStorage the user is considered authenticated. I have a button in the navbar for Login that brings up a modal login form. After the user is authenticated using the form, it is closed, but the button doesn't change to the Logout button. I have set it up to use a property on app.component called IsAuthenticated, which gets it's value from the authentication service isAuthenticated() method, which returns an Observable of type boolean indicating whether or not the user has been authenticated. But this property doesn't change when the user has been authenticated, even though the state has changed. I've tried a lot of things to get this to respond to the state change, but nothing has worked. Any help is appreciated!

authentication.service.ts (just isAuthenticated function):

public isAuthenticated(): Observable<boolean> {
  let token = localStorage.getItem('currentUser');
  if (token) {
    let tokenObject = JSON.parse(token);
    let expiresOn = moment(tokenObject.expires);
    // Confirm there is a token, and it's expiration is later than now
    let isLoggedIn = tokenObject.token !== '' && expiresOn > moment();
    return Observable.of(isLoggedIn);
  }
  return Observable.of(false);
}

app.component.ts:

export class AppComponent implements OnInit {
  public IsAuthenticated: boolean;
  loginModal: LoginComponent;

  constructor (
    private modalService: NgbModal,
    private authService: AuthenticationService
  ) { }

  openLogin(): void {
    this.modalService.open(LoginComponent, { size: 'sm' });
  }

  logout(): void {
    if (confirm('Are you sure you want to log out?')) {
      this.authService.logout();
      this.IsAuthenticated = false;
    }
  }

  ngOnInit() {
    this.authService.isAuthenticated()
      .subscribe(loggedIn => this.IsAuthenticated = loggedIn);
  }
}

app.component.html:

  <ul class="nav navbar-nav pull-right">
    <li class="nav-item">
      <button class="btn btn-primary" (click)="openLogin()" *ngIf="!IsAuthenticated">Login</button>
      <button class="btn btn-primary" (click)="logout()" *ngIf="IsAuthenticated">Logout</button>
    </li>
  </ul>

When the user clicks the "Login" button, the modal pops up, and I can login, but when it's done the Login button is still displayed, not the Logout, and I have other UI elements using the same ngIf that don't change either... What am I missing?

Upvotes: 0

Views: 771

Answers (1)

Bean0341
Bean0341

Reputation: 1697

Edited

Change *ngIf="isAuthenticated" to *ngIf="authService.isAuthenticated()", IsAuthenticated is a function so you must call it as such by adding the parenthesis and it is a function of your service so you must call the instance of the service as well.

Upvotes: 2

Related Questions