我有導航欄在我app.component.ts
,與ngIf
,所以登錄後,我應該看到註銷按鈕,但沒有發生變化,因爲app.component
沒有檢測到變化4種上檢測app.component
app.component.html:
<div>
<nav class='navbar navbar-default'>
<div class='container-fluid'>
<a class='navbar-brand'>{{title}}</a>
<ul class='nav navbar-nav'>
<li><a [routerLink]="['/welcome']">Home</a></li>
<li><a [routerLink]="['/apartments']">Apartments List</a></li>
</ul>
<div *ngIf="currentUser">
<p class="navbar-text navbar-right"><button (click)="logout()" class="btn btn-default">Log-out</button></p>
<p class="navbar-text navbar-right">Signed in as <a href="#" class="navbar-link">{{currentUser}}</a></p>
</div>
</div>
</nav>
</div>
<router-outlet></router-outlet>
app.component.ts:
import {Component, OnChanges} from '@angular/core';
import {AuthService} from "./shared/auth.service";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers:[AuthService]
})
export class AppComponent {
title = 'Product List App';
currentUser: string;
constructor(private _authService: AuthService) {
this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
}
logout() {
this._authService.logout();
this.currentUser = undefined;
}
}
當我進行登錄,我做的:localStorage.setItem('currentUser',JSON.stringify(user));
但我的app.component
未檢測到currentUser已更改,因此我無法看到登錄的用戶名和註銷按鈕。 (我需要做的刷新頁面中,爲了看到他們) 我怎樣才能解決這個不把登錄功能在我app.component.ts
?
什麼這樣做 'this.currentUser = JSON.parse(localStorage.getItem( 'currentUser') );' 在ngOnInit或ngViewLoaded中?而不是構造函數? –
https://plnkr.co/edit/YRz25z7uULhlXdfTlS30?p=preview我認爲這個問題是您的登錄,因爲在構造著作currentUser。 – chrisz
我怎麼觸發currentUser(在app.component)和 – Zakk