DEV Community

Cagkan Mert Oztas
Cagkan Mert Oztas

Posted on • Edited on

Implement Caching in Angular with HttpInterceptor

Caching with HttpInterceptor

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
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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);
        }
      })
    );
}
Enter fullscreen mode Exit fullscreen mode

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.


Check out my website for more...

Top comments (0)

Feature flag article image

Create a feature flag in your IDE in 5 minutes with LaunchDarkly’s MCP server 🏁

How to create, evaluate, and modify flags from within your IDE or AI client using natural language with LaunchDarkly's new MCP server. Follow along with this tutorial for step by step instructions.

Read full post