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
<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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.