Search code examples
angularexpresspassport.jsangular5passport-local

Angular 5: Hiding elements (if user isn't authenticated) not working


this is app.component.html

<nav class='navbar navbar-default'>
<div class='container-fluid'>
<div class="navbar-header">
  <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
  </button>
  <a class="navbar-brand" routerLink="" ></a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
  <ul class='nav navbar-nav navbar-left'>
    <li><a *ngIf="loggedin" routerLink="/posts">Posts</a></li>
    <li><a routerLink="/profile">Profile</a></li>
    <li><a *ngIf="loggedin" routerLink="/settings">Settings</a></li>
    <li><a routerLink="/register">Register</a></li>
    <li><a routerLink="/login">Login</a></li>
    <li><a routerLink="/administration">Administration</a></li>
  </ul>
</div>
</div>
</nav>

<router-outlet></router-outlet>

authentication.service.ts

import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {User} from "../../interfaces/user.interface";

@Injectable()
export class AuthenticationService {
logging: boolean = false;

constructor(private http: HttpClient) { }

isloggedin() {
this.http.get('/loggedin')
  .toPromise()
  .then((data: any) => {
    console.log('data', data);
    if (data) {
      return true;
    } else {
      return false;
    }

  });
 }

}

app.component.ts

import {Component, OnInit} from '@angular/core';
import {AuthenticationService} from 
"../../services/authentication/authentication.service";
import {HttpClient} from "@angular/common/http";
import {Observable} from "rxjs/Observable";

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
 })
export class AppComponent implements OnInit{
title = 'twittscheR';
loggedin: any;

constructor(private http: HttpClient) {
 this.loggedin = AuthenticationService.isloggedin();
}
ngOnInit(){
 this.loggedin = this.isloggedin();
}
isloggedin() {
 return this.http.get('/loggedin');
}
}

I'm really new to Angular 5. How can I implement, that some elements in the navbar are only visible, if loggedin is true? Even the page is reloaded. Login functionality is working, but ngIf does not update the variable in navbar

Thanks


Solution

  • Create an varibale loggedin of type BehaviorSubject<boolean> in your authentication.service.ts:

    loggedin: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(null);
    

    Now modife your isLoggedIn()-function so, that if you get data then set loggedin to true, if no data then set it to false;

    isloggedin() {
    this.http.get('/loggedin')
      .toPromise()
      .then((data: any) => {
        console.log('data', data);
        if (data) {
          // login success
          this.loggedid.next(true);
        } else {
          // login fails
          this.loggedid.next(false);
        }
    
      });
     }
    

    Now you can subscribe to loggedin varibale in your component. For that you should inject your authentication.service in app.component.ts.

    loggedin: boolean;
    
    constructor(private http: HttpClient, private authService: AuthenticationService) {
     this.authService.loggedin.subscribe(v => this.loggedin = v);
    }
    

    Now you can use loggedin variable from app.component.ts in your app.component.html.

    Beware: For bring this solution to work, you should run your isLoggedIn() function e.g. by clicking on login button.

    If you need more explanation, then let me know and I write larger tutorial.