Using $cacheFactory for API response caching

Loading

In AngularJS, frequent API calls can slow down application performance and increase server load. To optimize performance, we can use $cacheFactory to cache API responses, reducing redundant requests and improving response times.

This guide covers:
How $cacheFactory works
Caching API responses with $http
Manually managing cache entries
Best practices for using $cacheFactory


1. Understanding $cacheFactory in AngularJS

$cacheFactory is an in-memory cache mechanism that allows AngularJS applications to store and retrieve data efficiently. It prevents unnecessary HTTP requests by storing API responses locally.

Benefits of Caching API Responses:

  • Reduces network requests
  • Speeds up page load times
  • Improves user experience
  • Decreases server load

2. Creating a Cache Using $cacheFactory

To use $cacheFactory, you first create a cache instance.

Example: Creating a cache instance

var app = angular.module("myApp", []);

app.factory("dataCache", function($cacheFactory) {
return $cacheFactory("myDataCache"); // Creating a cache named 'myDataCache'
});

Here, myDataCache is the name of the cache storage. This cache instance can now store API responses.


3. Caching API Responses in $http

AngularJS supports caching natively in $http requests using the cache option.

Example: Enabling Cache in $http Requests

app.service("ApiService", function($http, $cacheFactory) {
var cache = $cacheFactory("apiCache");

this.getData = function() {
return $http.get("https://jsonplaceholder.typicode.com/posts", { cache: cache });
};
});

How It Works:

  • The first API call fetches data and stores it in the cache.
  • Subsequent calls use cached data instead of making a network request.

4. Manually Storing and Retrieving Data from Cache

Sometimes, you may need more control over what gets cached. $cacheFactory provides methods like:

  • put(key, value) → Store data in the cache
  • get(key) → Retrieve data from the cache
  • remove(key) → Delete a specific entry
  • removeAll() → Clear the entire cache

Example: Manually Storing and Retrieving Cached Data

app.service("ApiService", function($http, $cacheFactory) {
var cache = $cacheFactory("apiCache");

this.getCachedData = function(url) {
var cachedData = cache.get(url);
if (cachedData) {
console.log("Returning cached data");
return Promise.resolve(cachedData);
} else {
return $http.get(url).then(function(response) {
cache.put(url, response.data);
return response.data;
});
}
};
});

How It Works:
1️⃣ Checks if data exists in the cache
2️⃣ If yes, returns the cached response
3️⃣ If not, makes an HTTP request, stores the response in the cache, and returns it


5. Removing Cached Entries

To ensure cache does not store outdated data, clear cache entries when necessary.

Example: Removing Specific Cache Entries

app.service("ApiService", function($cacheFactory) {
var cache = $cacheFactory.get("apiCache");

this.clearCacheForUrl = function(url) {
cache.remove(url); // Removes only a specific entry
console.log("Cache cleared for:", url);
};
});

Example: Clearing All Cached Data

app.service("ApiService", function($cacheFactory) {
var cache = $cacheFactory.get("apiCache");

this.clearAllCache = function() {
cache.removeAll(); // Removes all cached entries
console.log("All cache cleared!");
};
});

Use Cases:
✔️ Clear cache when user logs out
✔️ Remove old data when refreshing dashboards
✔️ Avoid storing sensitive data permanently


6. Controlling Cache Size (Using Capacity)

By default, $cacheFactory stores unlimited entries. You can limit cache size using the capacity option.

Example: Setting Cache Capacity

app.factory("dataCache", function($cacheFactory) {
return $cacheFactory("myDataCache", { capacity: 10 }); // Stores only 10 items
});

How It Works:

  • If more than 10 entries are stored, older entries are removed automatically.
  • Helps in reducing memory usage in large applications.

Leave a Reply

Your email address will not be published. Required fields are marked *