¡Hola a todos!
En el desarrollo de aplicaciones frontend modernas, optimizar el rendimiento y la experiencia del usuario es fundamental. Una de las herramientas más potentes en Angular para manejar peticiones HTTP es el uso de interceptores. En este artículo, veremos cómo implementar una estrategia de caché para las peticiones HTTP utilizando interceptores.
¿Qué son los interceptores en Angular?
Los interceptores en Angular son una característica del HttpClient que permite interceptar y modificar las solicitudes y respuestas HTTP. Son ideales para implementar autenticación, manejo de errores y, como veremos en este caso, estrategias de caché.
Beneficios de implementar una estrategia de caché
Mejor rendimiento: Reduce el tiempo de respuesta al evitar solicitudes redundantes al servidor.
Disminución de carga en el backend: Menos peticiones significa menos carga para el servidor.
Mejor experiencia del usuario: Datos disponibles más rápidamente.
Paso a paso: Implementando un interceptor de caché
- Crear un servicio de caché
Primero, necesitamos un servicio que administre los datos cacheados.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CacheService {
private cache = new Map();
set(url: string, response: any, ttl: number = 7000): void { // Default TTL of 5 minutes
const expiration = Date.now() + ttl;
this.cache.set(url, { response, expiration });
}
get(url: string): any | undefined {
const cached = this.cache.get(url);
// If the response has expired, we delete the cache and return undefined
if (cached && cached.expiration > Date.now()) {
return cached.response;
} else {
this.cache.delete(url);
return undefined;
}
}
clear(): void {
this.cache.clear();
}
}
2. Crear el interceptor
El siguiente paso es crear un interceptor que utilice nuestro servicio de caché.
import { HttpInterceptorFn, HttpResponse } from '@angular/common/http';
import { inject } from '@angular/core';
import { CacheService } from './cache.service';
import { of, tap } from 'rxjs';
export const cachingInterceptor: HttpInterceptorFn = (req, next) => {
const cacheService = inject(CacheService);
if (req.method !== 'GET') {
return next(req);
}
const cacheKey = `${req.url}?${req.params.toString()}`;
// Check if there is a valid cached response
const cachedResponse = cacheService.get(cacheKey);
if (cachedResponse) {
return of(new HttpResponse({ body: cachedResponse, status: 200 }));
}
// If there is no cached response, continue with the HTTP request
return next(req).pipe(
tap(event => {
if (event instanceof HttpResponse) {
cacheService.set(cacheKey, event.body);
}
})
);
};
3. Registrar el interceptor
Finalmente, registramos el interceptor en el módulo principal de nuestra aplicación.
import { ApplicationConfig, withInterceptors } from '@angular/core';
export const appConfig: ApplicationConfig = {
providers: [
// ...necessary imports
provideHttpClient(withInterceptors([cachingInterceptor]))
};
Ejemplo completo en StackBlitz
¡Explora el ejemplo funcionando en vivo! Haz clic en el enlace para ver el proyecto en StackBlitz: Ejemplo de Interceptor de Caché.
Consideraciones adicionales
Caché por tiempo limitado: Puedes agregar un sistema de expiración a los datos cacheados. (TTL)
Excluir ciertas URLs: Configura reglas para no cachear datos sensibles o que cambian frecuentemente.
Pruebas: Asegúrate de probar a fondo tu estrategia de caché para evitar errores inesperados.
Con este enfoque, podrás optimizar significativamente tus aplicaciones Angular.
Реалізація стратегії кешування з використанням інтерсепторів не тільки покращує продуктивність, а й забезпечує більш плавний досвід для ваших користувачів.
Якщо цей матеріал виявився корисним, не забудьте поділитися ним та підписатися на мене, щоб отримувати більше контенту про Angular!
Перекладено з: Estrategias de Caché en Angular: Interceptores para un Rendimiento Óptimo