简体   繁体   English

在 angular 中无法在不刷新整个页面的情况下更新 Navbar 组件

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

I have a Navbar which has the following items:我有一个导航栏,其中包含以下项目:

Welcome欢迎

Admin行政

About关于

Source来源

Login登录

我附上了导航栏的图片

The first time the user is about to login the value for login is "Login" and as the user navigates to the Welcome component(or any other component) the value for login should change to the username passed.But on navigating to the Welcome component the value for the login on the navbar does not change and still displays "Login".用户第一次登录时,登录值是“登录”,当用户导航到欢迎组件(或任何其他组件)时,登录值应更改为传递的用户名。但是在导航到欢迎组件时导航栏上的登录值没有改变,仍然显示“登录”。 Only when I refresh the page the username is displayed.只有当我刷新页面时,才会显示用户名。 Not able to figure out what's wrong无法弄清楚出了什么问题

Below is what I have done:以下是我所做的:

navbar.component.html导航栏.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>

navbar.component.ts导航栏.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)

Login.component.ts登录.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)

} }

authentication.service认证服务

   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; }));
}

I have tried component interaction and change detection.我尝试过组件交互和变化检测。 Pretty sure I am missing something but not sure what it is.很确定我遗漏了一些东西,但不确定它是什么。 Any help would be appreciated.任何帮助,将不胜感激。

Actually in my case I am able to show the user detail but when I logged out and again logged in then old user's name is visible.实际上,就我而言,我能够显示用户详细信息,但是当我注销并再次登录时,旧用户名是可见的。 need to refresh the browser tab to show new logged in user name.需要刷新浏览器选项卡以显示新登录的用户名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM