Lakshman Pilaka
Lakshman Pilaka

Reputation: 1951

localstorage not getting refreshed in angular service

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.

Upvotes: 3

Views: 4084

Answers (2)

Lakshman Pilaka
Lakshman Pilaka

Reputation: 1951

I found the issue - this is the culprit:

const httpOptions

I have made it a variable in the class and am setting it in every method like:

export class LocationService {

  httpOptions: any;

  constructor(private http: HttpClient) {
  }


  getcities() {
    this.httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': 'Basic ' + JSON.parse(localStorage.getItem('userdetails')).token
      })
    };
    return this.http.get<any>('http://myservice.com/api/cities', this.httpOptions);
  }

.
.
.

Now, it's all fine.

Upvotes: 1

akosyjess
akosyjess

Reputation: 1

I got nearly the same issue, found out the I called localStorage in the declaration part that's why it came null. You should declare the variable first then if you have localstorage call it after the constructor. Thanks Lakshman!

service.ts header: any

constructor

header = localStorage....

Upvotes: 0

Related Questions