class StoreDataListener { targetProperty: string; handler: Function; } class StoreDataObserver { listeners: Array; constructor() { this.listeners = []; } observe(property, handler) { this.listeners.push({ targetProperty: property, handler: handler }); } notify(property, value) { this.listeners.forEach(listener => { if (listener.targetProperty === property) { listener.handler(value); } }); } } class LocalStoreService { private LOCAL_DATA_NAME = "utils_local_data"; private localData = localStorage.getItem(this.LOCAL_DATA_NAME) ? JSON.parse(localStorage.getItem(this.LOCAL_DATA_NAME)) : {}; Observer: StoreDataObserver = new StoreDataObserver(); getProperty(property) { return this.localData[property]; } setProperty(property, value) { this.localData[property] = value; localStorage.setItem(this.LOCAL_DATA_NAME, JSON.stringify(this.localData)); this.Observer.notify(property, value); } removeProperty(property) { this.localData[property] = null; delete this.localData[property]; localStorage.setItem(this.LOCAL_DATA_NAME, JSON.stringify(this.localData)); } observe(property, handler) { this.Observer.observe(property, handler); } clear() { this.localData = {}; localStorage.setItem(this.LOCAL_DATA_NAME, JSON.stringify(this.localData)); } addToArray(arrayProperty, object) { let array: Array = this.getProperty(arrayProperty) as Array; array.push(object); this.setProperty(arrayProperty, array); } runOnArray(arrayProperty, fn: Function) { let array: Array = this.getProperty(arrayProperty) as Array; array.forEach(item => fn(item) ); this.setProperty(arrayProperty, array); } saveFlashProperty(property, value) { this.setProperty("flash_" + property, value); } getFlashProperty(property) { let propertyValue = this.getProperty("flash_" + property); if (propertyValue) { propertyValue = JSON.stringify(propertyValue); this.removeProperty("flash_" + property); return JSON.parse(propertyValue); } else { return null; } } removeFlashProperty(property) { this.removeProperty("flash_" + property); } cleanFlashProperties() { Object.keys(this.localData).forEach(key => { if (key.indexOf("flash_") !== -1) { this.removeProperty(key); } }); } } export const LocalStorageService = new LocalStoreService();