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
});


Creating an angular service to share data between components

Create a Data store to save data as key and values. E.g:
export class DataStore {
private map = new Map<string, any>();
add(key: string, value: any) {
this.map.set(key, value);
}
hasKey(key: string) {
return this.map.has(key);
}
getValue(key: string) {
return this.map.get(key);
}
remove(key: string) {
if (this.hasKey(key)) {
this.map.delete(key);
return true;
} else {
return false;
}
}
}
view raw DataStore.ts hosted with ❤ by GitHub


Note: It uses build in Map data structure and it already has function to add, remove, delete and check objects.

Now let's create a service.
import { Injectable } from "@angular/core";
import { Subject, Observable } from "rxjs";
import { DataStore } from "../models/datastore.model";
import { environment } from "../../../environments/environment";
@Injectable({
providedIn: "root",
})
export class StorageService {
private _dataStore = new DataStore();
private readonly changes = new Subject<DataStore>();
constructor() {}
public get(): Observable<DataStore> {
// log in console if key exists in data store. In development mode only
if (environment.production === false) {
console.log("StorageService.get()", this._dataStore);
}
return this.changes.asObservable();
}
public store(key: string, data: any): void {
// check if object already exist in data store and remove it
if (this._dataStore.hasKey(key)) {
this._dataStore.remove(key);
}
this._dataStore.add(key, data);
this.changes.next(this._dataStore);
// log in console for each store method call. In development mode only
if (environment.production === false) {
console.log("StorageService.store() : DataStore:", key, this._dataStore);
}
}
public remove(key) {
// log in console if key exists in data store. In development mode only
if (environment.production === false) {
console.log(
"StorageService.remove() : DataStore has key:",
this._dataStore.hasKey(key)
);
}
if (this._dataStore.hasKey(key)) {
this._dataStore.remove(key);
this.changes.next(this._dataStore);
}
}
}


To store and save data call the service as:
// to store data
this._dataStorageService.store(
key, // string
object //any item
);
// to retrieve data, can be used any component
this._dataStorageService.get().subscribe((data) => {
console.log(data);
});