Skip to content

Instantly share code, notes, and snippets.

@miguelplazasr
Created October 7, 2021 12:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miguelplazasr/3d6f4c31ae5fa3f620155d92c3424497 to your computer and use it in GitHub Desktop.
Save miguelplazasr/3d6f4c31ae5fa3f620155d92c3424497 to your computer and use it in GitHub Desktop.
import { BehaviorSubject, Observable, Subject } from 'rxjs';
import { Inject, Injectable, OnDestroy } from '@angular/core';
export enum LocalStorageTypeEnum {
LOCAL_STORAGE,
SESSION_STORAGE,
}
export interface IKeyValuePair<K, T> {
key: K;
value: T;
}
@Injectable()
export class SessionStorageService implements OnDestroy {
private onSubject = new BehaviorSubject<IKeyValuePair<string, any>>(null);
public changes = this.onSubject.asObservable();
private window = window;
private storage: Storage = this.window.sessionStorage;
constructor() {
this.start();
}
ngOnDestroy() {
this.stop();
}
public getStorage() {
let s = [];
for (let i = 0; i < this.storage.length; i++) {
s.push({
key: this.storage.key(i),
value: JSON.parse(this.storage.getItem(this.storage.key(i))),
});
}
return s;
}
public setItem(key: string, data: any): void {
this.storage.setItem(key, JSON.stringify(data));
// the local application doesn't seem to catch changes to storage...
this.onSubject.next({ key: key, value: data });
}
public getItem(key: string): any | null {
const variable = this.storage.getItem(key);
if (variable == null) {
return null;
}
return JSON.parse(variable);
}
public clear(key) {
this.storage.removeItem(key);
// the local application doesn't seem to catch changes to storage...
this.onSubject.next({ key: key, value: null });
}
private start(): void {
this.window.addEventListener(
'storage',
this.storageEventListener.bind(this)
);
}
private storageEventListener(event: StorageEvent) {
if (event.storageArea === this.storage) {
let v;
try {
v = JSON.parse(event.newValue);
} catch (e) {
v = event.newValue;
}
this.onSubject.next({ key: event.key, value: v });
}
}
private stop(): void {
this.window.removeEventListener(
'storage',
this.storageEventListener.bind(this)
);
this.onSubject.complete();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment