Caching is a very useful feature to reduce server-side network traffic. It can reduce server requests by saving and receiving data on the client-side. Therefore, we will achieve more performance in the client application.
I mentioned how powerful angular HTTP tools are in my previous posts; HttpClient and HttpInterceptor. In this article, we will manage client-side caching through HTTP interceptors. We will create a simple HTTP interceptor in angular and cut all requests to the server. When we request the server for the first time, the interceptor saves the response data as a cache on the client-side and when the user requests the same URL again and cache exists, it does not go back to the server. Instead, client data is served from the cache. This implementation keeps the cache for 60 seconds but it is advisable to have a different cache clearance mechanism for real-life applications.
import { Injectable } from '@angular/core'; import { HttpEvent, HttpRequest, HttpHandler, HttpInterceptor, HttpResponse } from '@angular/common/http'; import { Observable, of } from 'rxjs'; import { tap, delay } from 'rxjs/operators'; @Injectable() export class CacheInterceptor implements HttpInterceptor { private cache = new Map<string, any>(); intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { if (request.method !== 'GET') { return next.handle(request); } const cachedResponse = this.cache.get(request.url); if (cachedResponse) { return of(cachedResponse); } return next.handle(request).pipe( tap(event => { if (event instanceof HttpResponse) { this.cache.set(request.url, event); } }), delay(60000), tap(() => this.cache.delete(request.url)) ); } }