Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear the cache while clearing localstorage

I have set a Authentication token in local storage on login and clears it on logout. After logout if the user tries to login again, old authentication token taken from the cache is taken instead of newly set value. How to clear the cache while clearing localstorage. I am using angular 2 in my application.

Login:

localstorage.setItem("token", "value")

Logout:

localstorage.clear();
like image 205
selvakumar Avatar asked Aug 30 '17 18:08

selvakumar


People also ask

Does clearing localStorage clear cache?

Local Storage data will not get cleared even if you close the browser. Because it's stored on your browser cache in your machine. Local Storage data will only be cleared when you clear the browser cache using Control + Shift + Delete or Command + Shift + Delete (Mac).

Does local storage clear automatically?

LocalStorage has no expiration time, Data in the LocalStorage persist till the user manually delete it. This is the only difference between LocalStorage and SessionStorage.

What does localStorage Clear () do?

The clear() method removes all the Storage Object item for this domain. The clear() method belongs to the Storage Object, which can be either a localStorage object or a sessionStorrage object.


1 Answers

before doing localstorage.clear();, you have to remove the element; To do that, your code should look like this: localStorage.removeItem('Token'); localstorage.clear();

Note that if you are using BehaviorSubject, you also have to set it to null; assume the following:

private loggedInUserSubject: BehaviorSubject<User>;
public loggedInUser: Observable<User>;

and in the constructor, to get the user's value:

this.loggedInUserSubject= new BehaviorSubject<User>(JSON.parse(localStorage.getItem('loggedInUser')));
this.loggedInUser= this.loggedInUserSubject.asObservable();

then to logout:

    localStorage.removeItem('currentUser');
    this.currentUserSubject.next(null);
    localstorage.clear();

Hope it helps :D

like image 77
TheCondorIV Avatar answered Nov 01 '22 21:11

TheCondorIV