Joe Berthelot
Joe Berthelot

Reputation: 735

Angular 6 - Update *ngIf after Component Loads

Component:

import { Component, OnInit } from '@angular/core';

// Services
import { AuthService } from './services/auth.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent implements OnInit {
  user: Object;
  authorized: boolean;

  constructor(private authService: AuthService) {}

  ngOnInit() {
    this.authorized = this.authService.loggedIn();
  }
}

HTML:

<app-navbar *ngIf="authorized"></app-navbar>

<div id="content"
     *ngIf="authorized">
    <app-sidebar></app-sidebar>

    <div class="wrapper full-width">
        <router-outlet></router-outlet>
    </div>
</div>

<div class="container mt-6"
     *ngIf="!authorized">
    <router-outlet></router-outlet>
</div>

this.authService.loggedIn(); returns true or false, which is used to display some elements in the *ngIf's of the HTML. The user gets redirected to this page after logging in, so the *ngIf's don't get read automatically. Instead you have to refresh the page for everything to update properly.

From my knowledge, I can't subscribe to the this.authService.loggedIn() due to it not being an observable so I'm not sure how to automatically update the view when the user first views the component. Here's the service itself for reference:

loggedIn() {
    if (localStorage.id_token === undefined ) {
      return false;
    } else {
      const helper = new JwtHelperService();
      return !helper.isTokenExpired(localStorage.id_token);
    }
  }

Upvotes: 1

Views: 1030

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73731

You can make sure that the authorized property is up to date by making it a getter:

public get authorized(): boolean {
  return this.authService.loggedIn();
}

Upvotes: 2

Related Questions