In my Angular app (5.2.3), I have implemented a feature to display a login/logout button in the top right corner of the page. The functionality involves silently logging the user in using an external Open ID Connect provider and then displaying the user's name and logout button upon callback. However, despite successful backend operations, the view fails to update accordingly.
Here is the relevant component view code snippet:
<ul class="navbar-nav">
<li class="nav-item" *ngIf="!loggedIn">
<a href="#" class="nav-link" (click)="login()">Login</a>
</li>
<li class="nav-item" *ngIf="loggedIn">
<a href="#" class="nav-link disabled" disabled>Hello, {{ name }}</a>
</li>
<li class="nav-item" *ngIf="loggedIn">
<a href="#" class="nav-link" (click)="logoff()">Logout</a>
</li>
</ul>
import {
Component,
OnInit,
SimpleChanges,
ApplicationRef,
ChangeDetectorRef,
NgZone
} from '@angular/core';
import {
OAuthService
} from 'angular-oauth2-oidc';
import {
SessionService
} from '../session.service';
@Component({
selector: 'app-navigation',
templateUrl: './navigation.component.html',
styleUrls: ['./navigation.component.css']
})
export class NavigationComponent implements OnInit {
name: string;
loggedIn: boolean;
constructor(private oauthService: OAuthService,
private sessionService: SessionService,
private applicationRef: ApplicationRef,
private zone: NgZone,
private cd: ChangeDetectorRef) {
//this.loggedIn = false;
}
ngOnInit() {
this.sessionService.state.subscribe(isLoggedIn => {
console.log('Detected a state change! User is logged in: ' + isLoggedIn);
this.zone.run(() => {
if (!isLoggedIn) {
this.name = null;
this.loggedIn = false;
console.log('User not logged in. Name is set to null');
} else {
const claims: any = this.oauthService.getIdentityClaims();
console.log(`Got claims. Name is now ${claims.name}`);
this.name = claims.name;
this.loggedIn = true;
}
});
this.cd.detectChanges();
this.applicationRef.tick();
});
this.sessionService.configureWithNewConfigApi();
}
public login() {}
public logoff() {}
}
console.log
statements are successfully executed, but unfortunately, the view does not reflect the updates as intended.