Angular HTTP Request Caching
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
-
NG0201: No provider for HttpClient!
cause You are attempting to use HttpClient in a component or service without providing it in the application's root providers.fixAdd `provideHttpClient()` (or `provideHttpClient(withInterceptorsFromDi())` if using interceptors) to the `providers` array in your `bootstrapApplication` call or `app.config.ts`. -
Error: NgHttpCachingInterceptor is not provided.
cause The `NgHttpCachingInterceptor` is not registered with Angular's HTTP interceptor system, likely because `provideNgHttpCaching()` was not called or `provideHttpClient(withInterceptorsFromDi())` is missing.fixEnsure both `provideNgHttpCaching()` and `provideHttpClient(withInterceptorsFromDi())` are present in your application's root `providers` array. If you are using NgModules, verify `NgHttpCachingModule.forRoot()` is imported.
Warnings
- breaking The library's major version closely follows Angular's major version. Upgrading Angular (e.g., from v14 to v15, or v15 to v16) likely requires upgrading `ng-http-caching` to its corresponding major version. This often introduces breaking changes in API surface or configuration, especially with the shift to standalone APIs.
- gotcha By default, the cache `version` is tied to Angular's major version. This means cache entries are automatically invalidated and cleared on every Angular upgrade. While generally beneficial for preventing stale data issues, be aware if you need more persistent caching across Angular versions or have a custom invalidation strategy.
- gotcha Forgetting to provide `provideHttpClient(withInterceptorsFromDi())` alongside `provideNgHttpCaching()` will result in the caching interceptor not being registered, and caching will not occur. This is a common pitfall when setting up Angular's HttpClient with interceptors in a standalone application.
- deprecated The `NgHttpCachingModule` (module-based approach) is deprecated for Angular 15+ standalone applications. While it might still work for applications using NgModules, the recommended approach is to use the new functional `provideNgHttpCaching` API.
Install
-
npm install ng-http-caching -
yarn add ng-http-caching -
pnpm add ng-http-caching
Imports
- provideNgHttpCaching
import { NgHttpCachingModule } from 'ng-http-caching'; // For Angular 15+ standalone APIsimport { provideNgHttpCaching } from 'ng-http-caching'; - NgHttpCachingConfig
import { NgHttpCachingConfig } from 'ng-http-caching'; - NgHttpCachingInterceptor
import { NgHttpCachingInterceptor } from 'ng-http-caching';
Quickstart
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.