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();
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).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With