![]()
What You’ll Learn
What is $cacheFactory in AngularJS?
How to use $cacheFactory to store API responses
Configuring $http service with caching
Managing and clearing cache
1️⃣ What is $cacheFactory?
$cacheFactory is a built-in AngularJS service that caches data in memory, reducing redundant API calls and improving app performance.
🔹 Why Use $cacheFactory?
- Speeds up API requests (avoids fetching the same data repeatedly)
- Reduces server load
- Enhances user experience (faster page loads)
2️⃣ Creating a Cache Using $cacheFactory
Step 1: Define a Cache
app.factory('apiCache', function ($cacheFactory) {
return $cacheFactory('myCache');
});
This creates a cache instance named "myCache".
3️⃣ Using $cacheFactory in $http Requests
Step 2: Cache API Responses in $http Calls
app.service('DataService', function ($http, apiCache) {
this.getData = function () {
return $http.get('/api/data', { cache: apiCache });
};
});
Now AngularJS caches the response, avoiding unnecessary server calls.
4️⃣ Enabling Built-in Caching in $http
AngularJS automatically caches GET requests when { cache: true } is enabled.
Step 3: Enable Caching in $http
app.service('DataService', function ($http) {
this.getData = function () {
return $http.get('/api/data', { cache: true });
};
});
AngularJS now caches GET requests internally.
5️⃣ Retrieving Cached Data Manually
Use $cacheFactory to retrieve data from the cache without making an HTTP request.
Step 4: Get Cached Data
var cachedData = apiCache.get('/api/data');
if (cachedData) {
console.log('Data from cache:', cachedData);
} else {
console.log('No data found in cache.');
}
Now you can check if data exists before making an API call!
6️⃣ Clearing Cache
Sometimes, cached data becomes outdated. Use $cacheFactory methods to clear it.
Step 5: Remove a Specific Cache Entry
apiCache.remove('/api/data');
Deletes cached response for /api/data only.
Step 6: Remove All Cache Entries
apiCache.removeAll();
Clears the entire cache.
Step 7: Destroy Cache Completely
apiCache.destroy();
Removes the cache instance permanently.
7️⃣ Example: Full Implementation
app.factory('apiCache', function ($cacheFactory) {
return $cacheFactory('myCache');
});
app.service('DataService', function ($http, apiCache) {
this.getData = function () {
var cachedData = apiCache.get('/api/data');
if (cachedData) {
console.log('Returning cached data');
return Promise.resolve({ data: cachedData });
} else {
return $http.get('/api/data', { cache: apiCache }).then(function (response) {
apiCache.put('/api/data', response.data);
return response;
});
}
};
this.clearCache = function () {
apiCache.remove('/api/data');
};
});
Optimized API calls with caching and clearing mechanisms.
