Это служба кэширования, которую я использую, она хранит данные в хранилище Redux, но ее легко поменять на любой нужный вам держатель данных.
@Injectable()
export class CacheManager {
constructor(
private store: NgRedux<IAppState>,
private actions: GlobalActions) {
}
public get<T>(key: CacheKey, thisArg: any, dataRetriver: (...args: any[]) => T | Observable<T>, ...args: any[]): Observable<T> {
if (this.isCached(key)) {
return of(this.getFromCache<T>(key));
}
const data$: T | Observable<T> = dataRetriver.apply(thisArg, args);
if (data$ instanceof Observable) {
return data$.pipe(
tap(result => this.addToCache(key, result))
);
}
else {
this.addToCache(key, data$);
return of(data$);
}
}
public clear(): void {
this.store.dispatch(this.actions.clearCache());
}
private isCached(key: string): boolean {
return this.cacheStorage[key] !== undefined;
}
private addToCache<T>(key: string, value: T): void {
this.store.dispatch(this.actions.cache(key, value));
}
private getFromCache<T>(key: string): T {
return <T>this.cacheStorage[key];
}
private get cacheStorage(): { [key: string]: any } {
return this.store.getState().global.cache;
}
}
и пример использования:
// call without cache:
this.service.loadPeriods(param1, param2)
.pipe(...)
.subscribe(...)
// call with cache ("periods" is a cache key):
this.cache.get("periods", this.service, this.service.loadPeriods, param1, param2)
.pipe(...)
.subscribe(...);