In-memory caching service with time-based expiration.
File: src/utils/services/cache.service.ts
import { Injectable } from '@angular/core';
interface CacheEntry<T = unknown> {
data: T;
timestamp: number;
}
const cacheDuration = 60 * 1000 * 60;
@Injectable({ providedIn: 'root' })
export class CacheService {
private cache = new Map<string, CacheEntry>();
setCache<T = unknown>(id: string, data: T) {
const entry: CacheEntry<T> = {
data,
timestamp: Date.now(),
};
this.cache.set(id, entry);
}
getCache<T = unknown>(id: string) {
const cachedResponse = this.cache.get(id);
if (cachedResponse && this.isCacheValid(cachedResponse)) {
return cachedResponse.data as T;
}
return;
}
private isCacheValid(cacheEntry: CacheEntry): boolean {
return Date.now() - cacheEntry.timestamp < cacheDuration;
}
}
The CacheService is an Angular service that provides simple in-memory caching with automatic expiration.
setCache(id: string, data: T): Stores data in cache with a unique identifier and current timestamp
getCache(id: string): Retrieves cached data if it exists and hasn't expired, returns undefined otherwise
Default cache duration is set to 60 minutes. Expired entries are automatically ignored during retrieval.
Angular Material Dev UI (or Angular Material Blocks) is one place stop for developers to explore components and blocks for their Angular Material and Tailwind CSS based applications.
Find us on X (Twitter), LinkedIn, Instagram & Threads