'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

I have attached a picture of the navbar

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

    <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

     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

      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.



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abhishek Parihar