Angular 6 - Update *ngIf after Component Loads

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



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.


this.authService.loggedIn();



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:


this.authService.loggedIn()


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





1 Answer
1



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


authorized


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





That seems to work great, but it broke the loading of other components. Now, when I try to navigate to another route, the route itself changes the the HTML or <router-outlet> content doesn't update until I do a page refresh. What could be causing the clicked route content to not load?
– Joe Berthelot
Aug 6 at 1:24





This code only gets the current value from the service. I don't know what causes the loading problem. You can check in the console to see if any error is reported.
– ConnorsFan
Aug 6 at 1:48





Instead of using ngIf to hide the router outlet, you may consider implementing a route guard to allow navigation only when the user is logged in.
– ConnorsFan
Aug 6 at 1:53


ngIf






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS