Friday, October 4, 2024
HomeTechnologyHow To Cache Http Request in Angular12 Example

How To Cache Http Request in Angular12 Example

How to cache http request in angular12 example is a powerful technique to improve the performance of web applications, especially in cases where the same data is frequently requested by the application. In Angular, caching HTTP requests can reduce server load, improve response times, and provide offline capabilities. In this article, we’ll explore how to cache HTTP requests in Angular 12 with a practical example.

1. Introduction how to cache http request in angular12 example

In web applications, caching refers to storing responses for future use so that the same data does not need to be fetched repeatedly from the server. how to cache http request in angular12 example that if a request has been made before, the cached response is returned instead of making a new request. This can save network bandwidth and reduce latency in the application.

Angular provides several ways to manage and cache HTTP requests using services like HttpClient and HttpInterceptors. We will focus on using HttpInterceptors to implement caching in this tutorial.

2. Benefits of Caching HTTP Requests

Caching HTTP requests offers numerous benefits for Angular applications, including:

  • Reduced Server Load: By serving cached data instead of making redundant server requests, server load is decreased.
  • Improved Performance: The user experience is improved with faster load times since the app doesn’t have to wait for a response from the server for cached requests.
  • Offline Access: In combination with other techniques (e.g., service workers), caching can help in delivering content when the app is offline.
  • Reduced Data Costs: Fewer HTTP requests mean reduced data usage, which is beneficial for users with limited or metered connections.

3. Setting Up an Angular 12 Project

Before we dive in how to cache http request in angular12 example, we need an Angular project to work with. If you don’t have an Angular 12 project set up, you can create one using the Angular CLI.

Step 1: Install Angular CLI

First, ensure you have Angular CLI installed globally:

bash
npm install -g @angular/cli

Step 2: Create a New Angular 12 Project

Now, create a new Angular project:

bash
ng new angular-http-cache-example
cd angular-http-cache-example

Step 3: Add HttpClientModule

To make HTTP requests, you need to import the HttpClientModule. Open src/app/app.module.ts and add the following:

typescript
import { HttpClientModule } from '@angular/common/http';

@NgModule({
declarations: [],
imports: [
HttpClientModule
],
bootstrap: []
})
export class AppModule { }


4. How to Implement HTTP Request Caching

The most effective way to handle caching in Angular is by using an HttpInterceptor. This allows you to intercept outgoing HTTP requests and incoming responses. You can then store the responses in memory and return them from the cache if the same request is made again.

Using Angular Interceptors for Caching

Angular’s HttpInterceptor interface allows you to define custom logic for every outgoing HTTP request. This makes it the ideal tool for implementing request caching.

Here’s how to create an interceptor for caching:

Step 1: Create an HTTP Cache Interceptor

In your Angular app, create a new file http-cache-interceptor.service.ts in the src/app directory.

typescript
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 HttpCacheInterceptor implements HttpInterceptor {
private cache = new Map<string, HttpResponse<any>>();

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Only cache GET requests
if (req.method !== 'GET') {
return next.handle(req);
}

// Check if request is already cached
const cachedResponse = this.cache.get(req.url);
if (cachedResponse) {
return of(cachedResponse);
}

// Send the request and cache the response
return next.handle(req).pipe(
tap(event => {
if (event instanceof HttpResponse) {
this.cache.set(req.url, event); // Cache the response
}
})
);
}
}

Step 2: Provide the Interceptor in the App Module

To use the HttpCacheInterceptor, it needs to be provided in the application’s root module.

Open app.module.ts and provide the interceptor in the providers array:

typescript
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpCacheInterceptor } from './http-cache-interceptor.service';

@NgModule({
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HttpCacheInterceptor,
multi: true
}
]
})
export class AppModule { }


In-Memory Cache Strategy

In this basic caching strategy, the responses are stored in memory using a Map. The key for each response is the request URL, and the value is the HttpResponse object. When the same request is made again, the interceptor checks if the URL is in the cache and returns the cached response if available.

If the requested data is not in the cache, the interceptor will allow the request to proceed to the server, cache the response, and return it.

5. Creating an Example Application

Let’s create a simple Angular component that fetches data using HTTP GET requests. This will allow us to demonstrate how the HTTP caching works.

Step 1: Create a Service for Fetching Data

Create a service called data.service.ts:

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

@Injectable({
providedIn: 'root'
})
export class DataService {
private apiUrl = 'https://jsonplaceholder.typicode.com/posts'; // Example API URL

constructor(private http: HttpClient) { }

getData(): Observable<any> {
return this.http.get(this.apiUrl);
}
}

Step 2: Create a Component to Display Data

Now, create a new component that will use the service to fetch and display data:

bash
ng generate component data

Open data.component.ts and modify it as follows:

typescript
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
selector: 'app-data',
templateUrl: './data.component.html',
styleUrls: ['./data.component.css']
})
export class DataComponent implements OnInit {
data: any[] = [];

constructor(private dataService: DataService) { }

ngOnInit(): void {
this.fetchData();
}

fetchData(): void {
this.dataService.getData().subscribe(response => {
this.data = response;
});
}
}

In the data.component.html, display the fetched data:

html
<div *ngFor="let item of data">
<h3>{{ item.title }}</h3>
<p>{{ item.body }}</p>
</div>

6. Advanced Techniques for HTTP Caching

Cache Invalidation

In a real-world application, cached data may become outdated. To handle this, you can introduce cache invalidation mechanisms, such as:

  • Time-based expiration: Automatically remove cached responses after a certain period.
  • Manual invalidation: Allow the cache to be cleared manually in specific scenarios (e.g., when user data changes).

Here’s how you can implement a basic time-based cache expiration:

typescript
class HttpCacheInterceptor implements HttpInterceptor {
private cache = new Map<string, { response: HttpResponse<any>, expiration: number }>();

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const cached = this.cache.get(req.url);
const isExpired = cached && cached.expiration < Date.now();

if (cached && !isExpired) {
return of(cached.response);
}

return next.handle(req).pipe(
tap(event => {
if (event instanceof HttpResponse) {
this.cache.set(req.url, { response: event, expiration: Date.now() + 60000 }); // 1-minute cache
}
})
);
}
}


7. Testing the HTTP Caching Functionality

Once you’ve implemented caching in your Angular app, it’s essential to test whether it’s working correctly. Here are some steps to verify the cache functionality:

  1. Open the Developer Tools in your browser and monitor the network activity.
  2. Make a request by loading the component. The first request should be sent to the server.
  3. Make the same request again by reloading the component or performing the action that triggers the request. This time, no new request should be made to the server (cached response).
  4. Clear the cache manually (optional) and ensure that new requests are sent after the cache is invalidated.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments