Angular HTTP Request Caching

21.0.10 · active · verified Wed Apr 22

NgHttpCaching is an Angular library designed to cache HTTP requests, preventing redundant server calls for the same data. It operates as an HTTP interceptor, automatically caching responses and serving them for subsequent identical requests. The current stable version is 21.0.10, closely aligning with Angular's major version releases (indicated by peer dependency versions and the default cache invalidation strategy). Key differentiators include built-in handling for simultaneous/parallel requests, an automatic garbage collector for cache entries, support for various storage mechanisms (LocalStorage, SessionStorage, MemoryStorage, or custom), and intelligent cache invalidation based on `Cache-Control`/`Expires` headers or automatically for mutation requests (POST, PUT, DELETE, PATCH). It offers granular configuration for cache lifetime, allowed HTTP methods, and custom cache strategies, making it a flexible solution for optimizing network performance in Angular applications.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate `ng-http-caching` into an Angular standalone application, providing custom configuration for cache lifetime and methods. It shows the basic setup required to enable HTTP request caching through the `provideNgHttpCaching` function and sets up a simple component to make an HTTP request that will be cached.

import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
import { AppComponent } from './app.component';
import { provideNgHttpCaching, NgHttpCachingConfig } from 'ng-http-caching';
import { HttpClient } from '@angular/common/http';
import { signal } from '@angular/core';

// Example application component
class AppComponent {
  data = signal<any>(null);
  constructor(private http: HttpClient) {}

  fetchData() {
    this.http.get('https://jsonplaceholder.typicode.com/posts/1').subscribe(res => {
      this.data.set(res);
      console.log('Fetched data:', res);
    });
  }
}

// Optional configuration for ng-http-caching
const ngHttpCachingConfig: NgHttpCachingConfig = {
  lifetime: 5000, // Cache entries expire after 5 seconds
  allowedMethod: ['GET'] // Only cache GET requests
};

bootstrapApplication(AppComponent, {
  providers: [
    provideNgHttpCaching(ngHttpCachingConfig), // Provide caching with custom config
    provideHttpClient(withInterceptorsFromDi()) // Provide HttpClient with interceptors
  ]
}).catch(err => console.error(err));

// To demonstrate caching, you would call fetchData() multiple times
// within the lifetime. The first call hits the network, subsequent calls
// within 5 seconds retrieve from cache.

view raw JSON →