簡體   English   中英

在 angular 中無法在不刷新整個頁面的情況下更新 Navbar 組件

[英]Unable to update Navbar component without refreshing the entire page in angular

我有一個導航欄,其中包含以下項目:

歡迎

行政

關於

來源

登錄

我附上了導航欄的圖片

用戶第一次登錄時,登錄值是“登錄”,當用戶導航到歡迎組件(或任何其他組件)時,登錄值應更改為傳遞的用戶名。但是在導航到歡迎組件時導航欄上的登錄值沒有改變,仍然顯示“登錄”。 只有當我刷新頁面時,才會顯示用戶名。 無法弄清楚出了什么問題

以下是我所做的:

導航欄.component.html

    <li class="dropdown">
        <a class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria- 
         expanded="false">{{username}}<span class="caret"></span></a>
        <ul class="dropdown-menu">
          <li class="active"><a (click)="logout()">Logout</a></li>
        </ul>
      </li>
    </ul>

導航欄.component.ts

     constructor(http: Http, public router: Router, private authService: AuthService) {
    this.username = localStorage.getItem('username');

    this.authService.UserName.subscribe(value =>{this.username = value;});
    console.log(this.username)

登錄.component.ts

      return this.authService.login(this.model.username, encrypted.toString())
        .subscribe(res => {
          this.authService.UserName.next("xyz");
            this.cdr.detectChanges();
            console.log(this.authService.UserName)

}

認證服務

   public login(username: string, password: string) {
    let authHeader = new Headers({ 'Content-Type': 'application/json' });
    let body = JSON.stringify({ username: username, password: password });
    return this.http.post(this.endPoint.AuthenticationUrl, body, { headers: authHeader })
        .pipe(map((response: Response) => {

            this.username = response.json().username;
            localStorage.setItem('username', this.username);
        },
        (err) => {this.handleError; }));
}

我嘗試過組件交互和變化檢測。 很確定我遺漏了一些東西,但不確定它是什么。 任何幫助,將不勝感激。

實際上,就我而言,我能夠顯示用戶詳細信息,但是當我注銷並再次登錄時,舊用戶名是可見的。 需要刷新瀏覽器選項卡以顯示新登錄的用戶名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM