Recently, I delved into the world of Angular with a goal to learn more about its functionality. I encountered an issue with my sidebar component that remains static even after logging in:
Click here to view my sidebar text
Upon successful login, the register and login texts should disappear and be replaced with the following:
Check out the updated sidebar post-login & refresh
The changes are only reflected when I manually refresh the page (using F5).
Interestingly, upon using the logout function, the sidebar updates correctly without requiring a manual refresh.
I am sharing some code snippets below that might shed light on the scenario:
side-bar.component.html
<p *ngIf="authService.isAuthenticated">{{message}}</p>
<li *ngIf="!authService.isAuthenticated"><a routerLink="/register">Register</a></li>
<li *ngIf="!authService.isAuthenticated"><a routerLink="/login">Login</a></li>
<li *ngIf="authService.isAuthenticated"><a routerLink="/home" (click)="logout()">Logout</a></li>
side-bar.component.ts
message = ''
ngOnInit() {
if(this.authService.isAuthenticated)
{
this.authService.getUser()
console.log("user is logged in")
this.message = `Welcome`
}
else
{
console.log("user is not logged in")
}
}
logout(): void {
this.authService.logout()
}
auth-service.service.ts
get isAuthenticated() {
return !!localStorage.getItem(this.TOKEN_KEY)
}
logout() {
localStorage.removeItem(this.TOKEN_KEY)
this.http.post(this.API_URL + '/logout', {})
this.router.navigateByUrl('/home')
}
login(user: string, pass: string) {
const data = {
username: user,
password: pass
}
this.http.post(this.API_URL + '/login', data, { withCredentials: true }).subscribe(
(res: any) => {
console.log(res)
localStorage.setItem(this.TOKEN_KEY, res.token.value)
this.router.navigateByUrl('/home')
}
)
}
getUser() {
this.http.get(this.API_URL + '/user', {withCredentials: true}).subscribe(
(res) => {
console.log(res)
}
)
}
If you have any suggestions, please do share them. Your input is highly appreciated.