import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { tap } from 'rxjs/operators'; import { CacheApiKey } from '../models/cache-api-key.enum'; import { of } from 'rxjs'; @Injectable({ providedIn: 'root', }) export class ServiceCacheApi { private cache: Map>; constructor() { this.cache = new Map>(); } public get(key: CacheApiKey, callToApi: Observable) : Observable { // console.log(`Get/push cache : ${CacheApiKey[key]}`); const cached = this.cache.get(key); if (cached) { return cached; } else { return callToApi.pipe( tap(event => { this.cache.set(key, of(event)); })); } } public delete(key: CacheApiKey) { // console.log(`Delete cache : ${CacheApiKey[key]}`); this.cache.delete(key); } public getByKey(key: CacheApiKey) : Observable { // console.log(`Get cache by key : ${CacheApiKey[key]}`); return this.cache.get(key); } }