In AngularJS, $cacheFactory
is a built-in service that helps cache data in memory, reducing unnecessary API calls and improving application performance. It is particularly useful when handling repeated requests, storing temporary data, or optimizing expensive computations.
1. What is $cacheFactory
?
$cacheFactory
creates and manages in-memory caches that store data for quick access, preventing redundant processing or network calls.
Example Use Cases
✔ Caching API responses to reduce network latency
✔ Storing computed results to avoid redundant calculations
✔ Keeping frequently accessed data available without re-fetching
2. Creating and Using a Cache
Creating a Cache
You can create a cache using $cacheFactory
:
var myApp = angular.module("myApp", []);
myApp.factory("dataCache", function ($cacheFactory) {
return $cacheFactory("dataCache"); // Creates a named cache
});
This cache instance (dataCache
) will store key-value pairs.
Storing and Retrieving Data
Once a cache is created, you can store and retrieve data easily:
myApp.controller("CacheController", function ($scope, dataCache) {
// Storing data
dataCache.put("username", "Narendra");
// Retrieving data
$scope.username = dataCache.get("username"); // Output: "Narendra"
});
This prevents repeated API calls for fetching the same data.
3. Managing Cached Data
Checking If a Key Exists
To check whether a key is stored in the cache:
if (dataCache.get("username")) {
console.log("Data exists in cache");
} else {
console.log("No cached data found");
}
Removing Cached Data
To remove a specific item from the cache:
dataCache.remove("username");
Clearing the Entire Cache
To remove all cached data:
dataCache.removeAll();
Checking Cache Size
To get the number of items in the cache:
console.log("Cache size:", dataCache.info().size);
4. Using $cacheFactory
with $http
for API Caching
When fetching data from an API, using $cacheFactory
with $http
improves performance by preventing duplicate requests.
Without Caching (Inefficient)
myApp.service("DataService", function ($http) {
this.getData = function () {
return $http.get("/api/data"); // Calls API every time
};
});
With Caching (Efficient)
Using $http
‘s built-in caching with $cacheFactory
:
myApp.service("DataService", function ($http, $cacheFactory) {
var httpCache = $cacheFactory("httpCache");
this.getData = function () {
return $http.get("/api/data", { cache: httpCache });
};
});
Now, duplicate API requests return cached data instead of making a network call.
5. Automatically Expiring Cache Data
Since $cacheFactory
does not automatically expire items, you need to manually clear outdated cache data.
Solution: Time-Based Expiry
myApp.factory("cacheService", function ($cacheFactory, $timeout) {
var cache = $cacheFactory("tempCache");
function putWithExpiry(key, value, ttl) {
cache.put(key, value);
// Remove cache after 'ttl' milliseconds
$timeout(function () {
cache.remove(key);
}, ttl);
}
return {
putWithExpiry: putWithExpiry,
get: cache.get,
remove: cache.remove,
removeAll: cache.removeAll
};
});
Here, putWithExpiry()
removes cached items after a specified time (ttl
).
6. Avoiding Common Pitfalls
Storing Large Data in Cache
✔ Cache only small, frequently accessed data. Avoid caching entire API responses if they contain large datasets.
Overusing $cacheFactory
for Permanent Storage
✔ $cacheFactory
only stores data in memory. Use localStorage
or sessionStorage
for persistent storage across sessions.
Forgetting to Clear Stale Cache
✔ Implement cache expiration logic or clear cache on data updates.