Come hang with us on Discord and chat directly with the team!Discordtop-bar-close-icon

2024-10-10

How to Cache HTTP Request in Angular 12 With Examples

tutorials
img

Introduction

Caching HTTP requests in Angular can significantly improve the performance of your application by reducing the number of redundant API calls. Angular provides several strategies to implement caching, leveraging tools like RxJS and HTTP interceptors. This article will guide you through an example of how to cache HTTP requests in Angular 12.

Using HTTP Interceptors

One effective way to cache HTTP requests in Angular is by using HTTP interceptors. Interceptors allow you to modify requests and responses globally, making them ideal for implementing caching logic. Here's a basic example of how you can set up an interceptor to cache HTTP responses:


import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class CacheInterceptor implements HttpInterceptor {
  private cache = new Map>();

  intercept(req: HttpRequest, next: HttpHandler): Observable> {
    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);
        }
      })
    );
  }
}

This interceptor checks if a GET request's response is already cached. If it is, it returns the cached response. Otherwise, it proceeds with the request and caches the response once received.

Using RxJS Operators

Another approach is to use RxJS operators like shareReplay to cache HTTP requests. This method is particularly useful when you want to cache responses across multiple subscriptions:


import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { shareReplay } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private data$: Observable;

  constructor(private http: HttpClient) {}

  getData(): Observable {
    if (!this.data$) {
      this.data$ = this.http.get('https://api.example.com/data').pipe(
        shareReplay(1)
      );
    }
    return this.data$;
  }
}

In this example, the shareReplay operator is used to cache the HTTP response, ensuring that the request is only made once and the response is shared among all subscribers.

Conclusion

Caching HTTP requests in Angular 12 can be efficiently achieved using HTTP interceptors and RxJS operators. These methods help reduce unnecessary API calls and improve application performance. By implementing these strategies, you can ensure that your Angular application runs smoothly and efficiently.