Angular: hide element when user is logged in

Viewed 9042

I'm trying to hide elements (buttons etc...) when the user is logged in.

Here is what I've got for the moment:

app.component.ts

import {Component, OnInit} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';
import {first} from 'rxjs/operators';

import {User} from './models/user.model';
import {UserService} from './services/user.service';
import {AuthenticationService} from "./services/authentication.Service";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  title = 'melanom-web';
  users: User[] = [];
  isAuthenticated: boolean;
  constructor(public authService: AuthenticationService, private translate: TranslateService, private userService: UserService) {
    translate.setDefaultLang('fr');
  }

  ngOnInit() {
    this.userService.getAll().pipe(first()).subscribe(users => {
      this.users = users;
    });
    this.isLoggedIn();
  }

  switchLanguage(language: string) {
    this.translate.use(language);
  }

  Logout() {
    this.authService.logout();
  }
  isLoggedIn() {
    this.isAuthenticated = this.authService.isLoggedIn();
  }
}

app.component.html

    <div class='container'>
  <div>
    <button (click)="switchLanguage('fr')"><img src="./src/assets/france.png" class="img-fluid"></button>
    <button (click)="switchLanguage('en')"><img src="./src/assets/uk.png" class="img-fluid"></button>
    <div class="float-right margin-top10">
        <button *ngIf="!authService.isLoggedIn()" type="button" routerLink="/register" class="btn btn-info margin-right">{{ 'Register' | translate }}</button>
        <button *ngIf="!authService.isLoggedIn()" type="button" routerLink="/login" class="btn btn-success">{{ 'Login' | translate }}</button>
    </div>
<div *ngIf="authService.isLoggedIn()">
    Users from secure api end point:
    <ul>
        <li *ngFor="let user of users">{{user.firstName}} {{user.lastName}}</li>
    </ul>
</div>
<p><a [routerLink]="['/login']">Logout</a></p>
  </div>
    <router-outlet></router-outlet>
</div>

authentication.service.ts

import {environment} from "../../environments/environment";
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {map} from 'rxjs/operators';

@Injectable({providedIn: 'root'})
export class AuthenticationService {
  isLoggedin: boolean = false;
  constructor(private http: HttpClient) {}

  login(username: string, password: string) {
    return this.http.post<any>(environment.apiUrl + '/users/authenticate', {username, password})
      .pipe(map(user => {
        // login successful if there's a jwt token in the response
        if (user && user.token) {
          // store user details and jwt token in local storage to keep user logged in between page refreshes
          localStorage.setItem('currentUser', JSON.stringify(user));
          this.isLoggedin = true;
        }

        return user;
      }));
  }

  logout() {
    // remove user from local storage to log user out
    localStorage.removeItem('currentUser');
    this.isLoggedin = false;
  }

  isLoggedIn() {
    debugger;
    if (localStorage.getItem("auth_token") == null) {
      this.isLoggedin = false;
      return this.isLoggedin;
    }
    else {
      return true;
    }
  }
}

this: *ngIf="!authService.isLoggedIn()" should hide my buttons when the user is logged. But it doesn't works... Does someone has a solution?

Thank you very much!!

3 Answers

Don't use function calls inside template, for that you have a property with name isAuthenticated

<div>
    <button *ngIf="!this.isAuthenticated" type="button" routerLink="/register" class="btn btn-info margin-right">{{ 'Register' | translate }}</button>
    <button *ngIf="!this.isAuthenticated" type="button" routerLink="/login" class="btn btn-success">{{ 'Login' | translate }}</button>
</div>
<div *ngIf="this.isAuthenticated">
    Users from secure api end point:
    <ul>
        <li *ngFor="let user of users">{{user.firstName}} {{user.lastName}}</li>
    </ul>
</div>

I think the problem is in your isLoggedIn() method,

as i can see you set token with currentUserbut in isLoggedIn method you are checking only auth_token

so try this,

isLoggedIn() {

    if (JSON.parse(localStorage.getItem('currentUser')).auth_token == null) {
      this.isLoggedin = false;
      return this.isLoggedin;
    }
    else {
      return true;
    }
  }

Your method in component must have one return

isLoggedIn() {
    this.isAuthenticated = this.authService.isLoggedIn();
    return this.isAuthenticated;
  }

So, you can use with an method:

<div *ngIf="isLoggedIn()">
    Users from secure api end point:
    <ul>
        <li *ngFor="let user of users">{{user.firstName}} {{user.lastName}}</li>
    </ul>
</div>

Or variable:

<div *ngIf="isAuthenticated">
    Users from secure api end point:
    <ul>
        <li *ngFor="let user of users">{{user.firstName}} {{user.lastName}}</li>
    </ul>
</div>
Related