import { Injectable } from '@angular/core'; /** * A wrapper around localStorage and sessionStorage * to improve ease of use and maintainability. * Works with JSON out of the box. */ @Injectable() export class StorageService{ store: Storage; id: string; local(){ this.store = localStorage; return this; } session(){ this.store = sessionStorage; return this; } init(initialValues: Object, storeType: 'local' | 'session' = 'local'){ //set store type this[storeType](); this.id = Math.floor(Math.random()*10000).toString(); this.store.setItem(this.id, JSON.stringify(initialValues)); } get(key?: string): any{ return (key.length > 0) ? JSON.parse(this.store.getItem(this.id))[key] : JSON.parse(this.store.getItem(this.id)); } set(key: string, value: any): StorageService; set(keyValue: Object): StorageService; set(keyOrKeyValue: string | Object, value?: any): StorageService{ if(typeof keyOrKeyValue == 'string'){ this.store.setItem(this.id, JSON.stringify(Object.assign({}, this.get(), { keyOrKeyValue: value }))); } else if(typeof keyOrKeyValue == 'object'){ this.store.setItem(this.id, JSON.stringify(Object.assign({}, this.get(), keyOrKeyValue))); } return this; } remove(key: string): void; remove(keys: string[]): void; remove(keyOrKeys: string | string[]): void{ let s = this.get(); if(typeof keyOrKeys == 'string'){ delete s[keyOrKeys]; } else{ keyOrKeys.forEach((k) => { delete s[k]; }) } this.set(s); } clear(): void{ return this.store.clear(); } }