Jul 15, 2020

Creating an angular service to share data between components using session storage

Create the session storage service as:
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:
// 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
});


No comments: