API response caching in AngularJS improves performance, reduces server load, and enhances user experience by storing previously fetched data instead of making repeated API calls. AngularJS provides built-in caching mechanisms using $http
and third-party solutions like $cacheFactory
.
1. Caching with $http
The $http
service in AngularJS supports automatic response caching using the cache
option.
a) Enable Caching for $http
Requests
app.factory("UserService", function($http) {
return {
getUsers: function() {
return $http.get("https://api.example.com/users", { cache: true });
}
};
});
🔹 The { cache: true }
option enables caching.
🔹 The first request fetches data from the server, and subsequent requests use cached data instead.
2. Using $cacheFactory
for Manual Caching
$cacheFactory
allows manual storage and retrieval of API responses.
a) Creating a Custom Cache
app.factory("UserCacheService", function($cacheFactory) {
return $cacheFactory("userCache");
});
🔹 This creates a custom cache named "userCache"
.
b) Caching API Responses
app.factory("UserService", function($http, UserCacheService) {
return {
getUsers: function() {
var cache = UserCacheService.get("users");
if (cache) {
return cache; // Return cached data if available
} else {
return $http.get("https://api.example.com/users").then(function(response) {
UserCacheService.put("users", response.data);
return response.data;
});
}
}
};
});
🔹 Checks cache before making an API request.
🔹 Stores response in the cache for later use.
3. Clearing Cached Data
To clear cache manually, use $cacheFactory.remove()
or $cacheFactory.removeAll()
.
a) Removing a Specific Cached Item
UserCacheService.remove("users");
b) Removing All Cached Items
UserCacheService.removeAll();
🔹 Useful when data updates frequently, requiring fresh API responses.
4. Caching with $resource
For RESTful APIs, $resource
also supports caching.
app.factory("UserService", function($resource, $cacheFactory) {
var userCache = $cacheFactory("userCache");
return $resource("https://api.example.com/users/:id", { id: "@id" }, {
get: { method: "GET", cache: userCache }
});
});
🔹 $resource
caches GET requests automatically if cache is provided.
5. When to Use Caching?
✔ Use caching for read-heavy APIs like user lists, product catalogs, or dashboards.
✔ Do not cache frequently updating data like stock prices or chat messages.
✔ Set an expiration policy if cached data must be refreshed after a specific time.