The user logs into the application where it checks for the loginID. If validated, the user details are returned through the authentication service. Now I am setting firstName, lastName, and id in sessionStorage to display the name on the sidebar immediately as user logs in. But firstName and lastName are only displayed either on home page refresh else it displays nothing or the previous user's name. On logout, I am removing the items from the sessionStorage. Login Routing code
this.authenticationService.login(this.username)
.pipe(first())
.subscribe(
data => {
this.router.navigate([this.returnUrl]);
},
Routing Code:
{ path: '', component: HomepageComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent, },
{ path: 'homepage', component: HomepageComponent, canActivate: [AuthGuard]},
AuthGuard Code:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const currentUser = this.authenticationService.currentUserValue;
if (currentUser) {
return true;
}
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
}
Code:
function authenticate() {
const { username } = body;
const user = users.find(x => x.username === username);
if (!user) return error('wrong username');
return ok({
id: user.id,
username: user.username,
firstName: user.firstName,
lastName: user.lastName,
token: 'fake-jwt-token'
})
Authentication Service on login and logout. At login, the username is passed to the login method and then sent for validation to authenticate method. The response is then returned.
login(username: string) {
return this.http.post<any>(`${environment.api}/users/authenticate`, { username })
.pipe(map(user => {
sessionStorage.setItem('firstName', JSON.stringify(user.firstName));
sessionStorage.setItem('lastName', JSON.stringify(user.lastName));
sessionStorage.setItem('id', JSON.stringify(user.id));
this.currentUserSubject.next(user);
return user;
}));
}
logout() {
sessionStorage.removeItem('firstName');
sessionStorage.removeItem('lastName');
sessionStorage.removeItem('id');
this.currentUserSubject.next(null);
}
In sidebar typescript:
ngOnInit() {
this.firstName = JSON.parse(sessionStorage.getItem('firstName'));
this.lastName = JSON.parse(sessionStorage.getItem('lastName'));
}
In sidebar HTML:
<p>Welcome {{firstName}} {{lastName}}</p>
I want the sessionStorage to remove the previous details as soon as the user logs out. And next user's name to be displayed as soon as the user logs in. It should not display name on page refresh after entering the page.