Jul 15, 2020

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


No comments: