Using $cacheFactory to store temporary data

Loading

In AngularJS, $cacheFactory is used to store and retrieve temporary data efficiently. It helps reduce redundant computations, network requests, and improves application performance.


1. Why Use $cacheFactory?

Improves Performance – Stores data locally to avoid redundant API calls.
Reduces Server Load – Cached data prevents unnecessary network requests.
Optimizes Computations – Stores frequently used results for quick access.
Increases Application Speed – Reduces response time by serving data from cache.


2. Creating a Cache Using $cacheFactory

You can create a cache using $cacheFactory inside a service or controller.

app.factory('CacheService', function($cacheFactory) {
return $cacheFactory('myCache');
});

Here, myCache is the name of the cache instance.


3. Storing and Retrieving Data from Cache

Once the cache is created, you can store and retrieve values.

app.controller('CacheController', function($scope, CacheService) {
// Storing data
CacheService.put('username', 'Narendra');

// Retrieving data
$scope.username = CacheService.get('username'); // 'Narendra'
});

4. Checking if a Key Exists in Cache

To check if a key exists, use .get().

if (CacheService.get('username')) {
console.log('User exists in cache:', CacheService.get('username'));
} else {
console.log('User not found in cache');
}

5. Removing Cached Data

Use .remove() to delete a specific key.

CacheService.remove('username');
console.log(CacheService.get('username')); // undefined

To remove all cached data, use .removeAll().

CacheService.removeAll();

6. Setting Cache Expiry (Timeout)

By default, $cacheFactory does not expire items. You can manually handle expiry using $timeout.

app.controller('CacheTimeoutController', function($scope, CacheService, $timeout) {
CacheService.put('sessionData', 'Temporary Value');

// Auto-remove after 5 seconds
$timeout(function() {
CacheService.remove('sessionData');
}, 5000);
});

7. Using $http with Caching

AngularJS allows caching HTTP responses using $http with $cacheFactory.

app.factory('DataService', function($http, $cacheFactory) {
var httpCache = $cacheFactory.get('$http');

return {
fetchData: function() {
return $http.get('https://api.example.com/data', { cache: httpCache });
}
};
});

Benefits:
API response is stored in cache.
Subsequent requests use cached data instead of making a new request.


8. Clearing Cache on User Logout

To reset the cache when a user logs out:

app.controller('LogoutController', function(CacheService) {
CacheService.removeAll();
console.log('Cache cleared on logout');
});

9. Checking Cache Info

You can check cache statistics using .info().

console.log(CacheService.info());

Output:

{
"id": "myCache",
"size": 2
}

Leave a Reply

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