Caching HTTP Responses
Caching HTTP responses can improve the performance of your Angular application by reducing the number of HTTP requests made to the server. This guide covers the basics of caching HTTP responses using HTTP interceptors.
Setting Up HTTPClientModule
First, import the HttpClientModule
into your app module:
// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { DataService } from './data.service';
import { HomeComponent } from './home/home.component';
import { CachingInterceptor } from './caching.interceptor';
@NgModule({
declarations: [AppComponent, HomeComponent],
imports: [BrowserModule, HttpClientModule],
providers: [
DataService,
{ provide: HTTP_INTERCEPTORS, useClass: CachingInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }
Creating an Interceptor
Create an interceptor to manage caching using the Angular CLI command:
$ ng generate interceptor caching
This command generates a new interceptor file named caching.interceptor.ts
.
Implementing the Interceptor
In the interceptor file, implement the HttpInterceptor
interface and define the intercept
method to cache HTTP responses:
// caching.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable()
export class CachingInterceptor 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 => {
this.cache.set(req.url, event);
})
);
}
}
Using the Interceptor
HTTP interceptors are automatically applied to all HTTP requests made using the HTTPClient. You don't need to do anything special in your components to use them. Here's an example component that makes HTTP requests:
// home.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
@Component({
selector: 'app-home',
template: `
Posts
- {{ post.title }}
`
})
export class HomeComponent implements OnInit {
posts: any[] = [];
constructor(private dataService: DataService) {}
ngOnInit() {
this.dataService.getPosts().subscribe(data => {
this.posts = data;
});
}
}
Handling Cache Invalidation
To handle cache invalidation, you can modify the interceptor to clear the cache when a non-GET request is made:
// caching.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable()
export class CachingInterceptor implements HttpInterceptor {
private cache = new Map();
intercept(req: HttpRequest, next: HttpHandler): Observable> {
if (req.method !== 'GET') {
this.cache.clear();
return next.handle(req);
}
const cachedResponse = this.cache.get(req.url);
if (cachedResponse) {
return of(cachedResponse);
}
return next.handle(req).pipe(
tap(event => {
this.cache.set(req.url, event);
})
);
}
}
Key Points
- Caching HTTP responses can improve the performance of your Angular application by reducing the number of HTTP requests made to the server.
- Import
HttpClientModule
in your app module to set up the HTTP Client. - Create an interceptor by implementing the
HttpInterceptor
interface to manage caching. - Use interceptors to cache HTTP responses and handle cache invalidation.
- Register interceptors in your app module using the
HTTP_INTERCEPTORS
token.
Conclusion
Caching HTTP responses is a powerful technique for improving the performance of your Angular applications. By setting up interceptors, you can efficiently manage caching and enhance the user experience. Happy coding!