Create the session storage service as:
To store and retrieve the session storage data, use the service as:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable, OnDestroy, OnInit } from "@angular/core"; | |
import { ReplaySubject } from "rxjs"; | |
import { environment } from "../../../environments/environment"; | |
@Injectable({ | |
providedIn: "root", | |
}) | |
export class StorageService implements OnInit, OnDestroy { | |
private storageChange$: ReplaySubject<{ | |
key: string; | |
value: string; | |
}> = new ReplaySubject(); | |
constructor() {} | |
ngOnInit() { | |
sessionStorage.clear(); | |
localStorage.clear(); | |
} | |
ngOnDestroy() { | |
this.storageChange$.unsubscribe(); | |
} | |
public store(key: string, data: any): void { | |
// log in console for each store method call. In development mode only | |
if (environment.production === false) { | |
console.log("StorageService.store():", key, sessionStorage); | |
} | |
sessionStorage.setItem(key, JSON.stringify(data)); | |
this.storageChange$.next({ key: key, value: JSON.stringify(data) }); | |
} | |
public get() { | |
// log in console if key exists in data store. In development mode only | |
if (environment.production === false) { | |
console.log("StorageService.get()", sessionStorage); | |
} | |
//window[area].getItem(key); | |
return this.storageChange$; | |
} | |
} |
To store and retrieve the session storage data, use the service as:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// to store data | |
this._storageService.store( | |
key, // as string | |
object // any object to store | |
); | |
// to retrieve data | |
this._storageService | |
.get() | |
.pipe( | |
filter(({ key }) => key === KEY_AS_STRING), | |
map((data) => { | |
return JSON.parse(data.value) as Object; | |
}) | |
) | |
.subscribe((data) => { | |
// use data | |
}); |