I have a menu to appear based on being logged. I am using json web tokens in local storage for my authentication, I want to watch for a change to localStorage and then re-update my view on new information.
How can I watch for changes to localstorage?
I set my localStorage with this
localStorage.setItem('jwt', my_token); The things I would like to do is check if I have a token, if I don't nothing happens, but when there is a change fire an event. From what I know I have to create a service, inject it where I want and susbscribe me to the observable.
What I have is the service, I don't know how to watch for the changes.
my service is:
import { Injectable } from 'angular2/core';
@Injectable()
export class LocalStorageService {
private storage: any;
constructor() {
this.storage = localStorage;
}
public retrieve(key: string): any {
var item = this.storage.getItem(key);
if (item && item !== 'undefined') {
return JSON.parse(this.storage.getItem(key));
}
return;
}
public store(key: string, value: any) {
this.storage.setItem(key, JSON.stringify(value));
}
}