Angular 2 Conditional Display

I have a function, loggedIn(), that returns a function built in to angular2-jwt called tokenNotExpired(). If tokenNotExpired() returns true, the person is logged in (has a JWT assigned to them) and certain parts of my app are shown hidden based on this. On page load, the page shows the elements correctly. If I’m logged in and then logout, the parts of the page are hidden that should be, but if I am logged out and then log in, nothing changes until a hard refresh.

It seems like if it works one way, it should work the other way too. Am I missing something? Is there something with change detection that I’m missing? I’ll put my code below, but it’s pretty basic stuff.

session.ts

import {tokenNotExpired} from 'angular2-jwt';
loggedIn() {
    return tokenNotExpired();
}

app.ts

loggedIn() {
    return this._session.loggedIn();
}

Then in the template I have *ngIf="loggedIn()" or *ngIf="!loggedIn()" on the parts that I want to show/hide, respectively. I’ve also tried *ngIf="loggedIn() == true" or *ngIf="loggedIn() == false", just in case.

******Edit*******

Just as an extra part of the code, I thought this might help:

login() {
    this.lock.show((error: string, profile: Object, id_token: string) => {
        if (error) {
            console.error(error);
        }
        localStorage.setItem('profile', JSON.stringify(profile));
        localStorage.setItem('id_token', id_token);
        this._router.navigate(['Dashboard']);
    });
}

That’s the login function, using Auth0 and their lock widget to login.

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

I figured out what to do to fix the issue. In my case at least, I needed to use NgZone and call the run function after logging in. From what I understand, the login was happening without the components knowing about it. using NgZone.run() re-rendered the components and the values were all updated appropriately.

This may not work in all situations, but it did work in this case.