i am using angular 6 and localStorage for saving auth token.
the code which gets authtoken from localStorage is:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Basic ' + JSON.parse(localStorage.getItem('userdetails')).token
})
};
and use it as
getCities() {
return this.http.get<any>('http://myservice.com/api/cities', httpOptions);
}
when i log out i am clearing localStorage and redirecting to home page as
localStorage.clear();
this.router.navigate(['/']);
when i login, i am setting the userdetails localStorage item as
this.loginService.login(obj)
.subscribe(
auth => {
localStorage.setItem('userdetails', JSON.stringify(auth));
this.router.navigate(['authentication/auth/redirectpage']);
}
);
My auth object i am saving is like this:
{"fullname":"Test User","username":"TestUser1","authlevel":"Q","designation":"Tester 1","token":"First_Login_Token"}
When i first login, everything is working fine. When i logout, userdetails localStorage element is getting destroyed (when checked in the Local Storage in Application tab of Chrome DevTools.
When i relogin with different user, my userdetails is getting updated properly to
{"fullname":"Test User 2","username":"TestUser2","authlevel":"R","designation":"Tester 2","token":"Second_Login_Token"}
BUT
localStorage.getItem('userdetails')).token in locationService returns First_Login_Token only.
If i reload the page, it is properly taking
Second_Login_Token.
Unsure of what is going wrong.