Learn how to implement caching with HttpInterceptor in Angular for improved performance and speed. Angular offers the HttpInterceptor class to intercept HTTP requests and cache responses. Follow these simple steps to implement caching with Angular HttpInterceptor:
Take a quick look: Edit on StackBlitz ⚡️
1) Create a new Angular interceptor.
ng generate interceptor cache
2) Check if the request is cacheable by verifying it’s a GET request.
private cache = new Map<string, any>();
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.method !== 'GET') {
return next.handle(req);
}
// your code here
}
3) Response should be already in cache using the Map object.
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.method !== 'GET') {
return next.handle(req);
}
const cachedResponse = this.cache.get(req.url);
if (cachedResponse) {
return of(cachedResponse);
}
// your code here
}
4) If the response is not in cache, send the request to the server and store the response in cache using the tap operator.
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.method !== 'GET') {
return next.handle(req);
}
const cachedResponse = this.cache.get(req.url);
if (cachedResponse) {
return of(cachedResponse);
}
return next.handle(req).pipe(
tap(event => {
if (event instanceof HttpResponse) {
this.cache.set(req.url, event);
}
})
);
}
By using caching with HttpInterceptor in Angular, you can reduce server calls and enhance the performance of your application. Optimize your Angular app now with this helpful caching technique.
Top comments (0)