Angular 2 – Component variable from service is not changed in the view

I have MainMenuComponent with some navigation links.
Some links are for signed members, some for guests, and some for everyone.

My master template (master.html) looks like this:

<main-menu></main-menu>

<div class="container">
<router-outlet></router-outlet>
</div>

inside my router-outlet, I have a login component. When I login, I change my JwtService.jwtToken variable to the user token. (a service variable)

That means that after login, I can still see the “Login” and “Register” menu links:

<li *ngIf="!JwtService.getToken()" [class.active]="isRouteActive(['/Login'])"><a [routerLink]="['Login']">Login</a></li>
        <li *ngIf="!JwtService.getToken()" [class.active]="isRouteActive(['/Register'])"><a [routerLink]="['Register']">Register</a></li>
        <li *ngIf="JwtService.getToken()" [class.active]="isRouteActive(['/Fight'])"><a [routerLink]="['Fight']">Fight</a></li>
        <li *ngIf="JwtService.getToken()"><a (click)="logOut()">Log Out</a></li>

Why does JwtService.getToken() is changed in my <router-outlet> but outside it, in my main menu component, its not updating? (unless I refresh the page manually)

**In other words: When my service variable is changed after login using jwtService.setToken("MY_TOKEN");
,The following expression in my view is not changed:

JwtService.getToken()

and it remains null until I refresh my browser/route **

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 had the same issue with components outside the router-outlet in Angular2 caused by zones and change detection strategy.

You can force Angular2 to check the full component tree by using the ApplicationRef.tick() method.

In your login component:

Add the reference to ApplicationRef

import {ApplicationRef} from 'angular2/core';

inject the ApplicationRef into the constructor:

constructor(public appRef: ApplicationRef)

then when you receive the response from the authentication service force the Angular2 app to go through the change detection again:

this.appRef.tick(); // this will refresh the bindings

Your main-menu component should get updated as expected.