How To Cache Http Request In Angular12 Example

8 min read Oct 12, 2024
How To Cache Http Request In Angular12 Example

How to Cache HTTP Requests in Angular 12 - A Practical Guide

Angular applications often make repeated requests to the same API endpoints, especially when dealing with data that doesn't change frequently. This can lead to unnecessary network calls and slow down your application. Caching HTTP requests in Angular can significantly improve performance by storing responses locally and reusing them for subsequent requests. This guide will walk you through the process of caching HTTP requests in Angular 12, providing a clear example and best practices.

Why Cache HTTP Requests in Angular 12?

Caching HTTP requests offers several benefits for your Angular application:

  • Improved performance: By reducing the number of network requests, your application will load faster and respond more quickly to user interactions.
  • Reduced server load: Caching helps distribute the workload, reducing the strain on your backend servers.
  • Improved user experience: Users will notice a smoother and faster application experience, leading to increased satisfaction.

Implementing HTTP Request Caching in Angular 12

Let's dive into a practical example using Angular's built-in HttpClient service and the @angular/common/http package.

1. Set Up Your Angular Project:

If you don't have an existing Angular 12 project, create one using the Angular CLI:

ng new my-angular-app
cd my-angular-app

2. Create a Caching Service:

Let's create a service named caching.service.ts within the src/app directory:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map, shareReplay, refCount } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class CachingService {
  private cache = new Map>();

  constructor(private http: HttpClient) { }

  get(url: string, options?: any, cacheTime = 60000): Observable {
    const cachedResponse = this.cache.get(url);

    if (cachedResponse) {
      console.log(`[CachingService] Returning cached response for ${url}`);
      return cachedResponse;
    } else {
      console.log(`[CachingService] Fetching data from server for ${url}`);
      const request = this.http.get(url, options)
        .pipe(
          shareReplay(1),
          refCount()
        );

      this.cache.set(url, request);

      // Automatically clear the cache after a specified duration (default: 60 seconds)
      setTimeout(() => {
        this.cache.delete(url);
      }, cacheTime);

      return request;
    }
  }
}

Explanation:

  • cache: This Map object stores cached responses keyed by the request URL.
  • get(url, options, cacheTime): This method checks if the response for a given URL exists in the cache. If found, it returns the cached response. Otherwise, it fetches data from the server, caches it for the specified cacheTime, and then returns the data.
  • shareReplay(1): This operator creates a shared observable that broadcasts the latest value to all subscribers. This helps optimize resource usage and avoid unnecessary requests.
  • refCount(): This operator ensures that the observable is only subscribed to when there are active subscribers.

3. Utilize the Caching Service:

Now, let's use the CachingService in a component to fetch data. Create a component named home.component.ts in your src/app directory:

import { Component } from '@angular/core';
import { CachingService } from './caching.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent {

  data: any;

  constructor(private cachingService: CachingService) { }

  ngOnInit() {
    this.cachingService.get('https://api.example.com/data').subscribe(data => {
      this.data = data;
    });
  }
}

4. Customize Cache Duration:

You can adjust the cacheTime parameter in the CachingService to specify the cache duration for specific requests:

this.cachingService.get('https://api.example.com/data', null, 300000); // Cache for 5 minutes 

5. Cache-Busting:

To ensure that you receive updated data when necessary, you can implement a mechanism to clear the cache. You can achieve this by:

  • Using unique request parameters: Append a timestamp or a unique identifier to your request URL, forcing the server to treat each request as a new one.
  • Manually invalidating the cache: Provide an option within your application to manually clear the cache for specific data points.

Example Usage:

// Get data from API with caching
this.cachingService.get('https://api.example.com/data').subscribe(data => {
  console.log('Data from API:', data);
});

// ... later on ...

// Update data in the cache
this.cachingService.get('https://api.example.com/data?timestamp=' + Date.now()).subscribe(data => {
  console.log('Updated Data from API:', data);
});

Important Considerations:

  • Cache Size: Monitor the size of your cache to avoid excessive memory usage. You might need to implement a cache eviction strategy to remove older or less frequently accessed data.
  • Data Expiration: If your data has a limited expiration time, consider updating the cache accordingly to avoid serving outdated information.
  • Cache Invalidation: Implement a robust cache invalidation strategy to ensure that your cached data remains consistent with the data on your backend.

Conclusion:

Caching HTTP requests in Angular 12 is a crucial optimization technique that can significantly enhance your application's performance and user experience. By following the steps outlined in this guide, you can easily implement caching in your Angular projects, ensuring that your application runs smoothly and efficiently.

Featured Posts