Using $cacheFactory for temporary storage

Loading

In AngularJS, $cacheFactory provides a simple in-memory cache that can be used for storing and retrieving data temporarily. This cache is particularly useful when you need to store results of expensive operations, API responses, or any data that can be reused to avoid making redundant requests, thus improving performance. It can help reduce the number of HTTP requests, enhance user experience, and optimize the application.

Let’s dive deeper into how $cacheFactory can be implemented for temporary storage in AngularJS.


What is $cacheFactory?

$cacheFactory is a service in AngularJS that allows you to create and manage custom caches. It provides a set of methods to store, retrieve, and manage data in memory, such as:

  • put(key, value) – Stores a value in the cache.
  • get(key) – Retrieves a value from the cache.
  • remove(key) – Removes a specific item from the cache.
  • removeAll() – Clears all items in the cache.
  • info() – Returns information about the cache, such as the number of entries.

Why Use $cacheFactory?

  1. Improve Performance: Reduce the number of API calls by caching frequently requested data. For example, if your application makes multiple calls to fetch the same resource, caching that data after the first call can reduce load times and server requests.
  2. Store Temporary Data: $cacheFactory is suitable for storing temporary data such as user preferences, application states, or search results that don’t need to be persisted long-term.
  3. Simplify Data Management: Using a cache helps reduce redundant code by avoiding re-fetching or re-calculating the same data multiple times.
  4. Custom Cache Control: With $cacheFactory, you can manually clear or refresh cached data when necessary.

How to Use $cacheFactory for Temporary Storage

Here’s a step-by-step guide on how to use $cacheFactory for temporary storage in AngularJS:

1. Inject $cacheFactory into Your Controller or Service

To begin using the cache, you need to inject $cacheFactory into your controller or service.

angular.module('myApp', [])
.controller('MyController', function($scope, $cacheFactory) {
// Cache logic will go here
});

2. Creating a Cache

You can create a cache using $cacheFactory with a specific name for the cache. The cache will be available throughout the scope of the AngularJS application until you explicitly remove it.

angular.module('myApp', [])
.controller('MyController', function($scope, $cacheFactory) {
// Creating a cache with a specific name 'myCache'
var myCache = $cacheFactory('myCache');
});

3. Adding Items to the Cache

You can use the put() method to store data in the cache. The put() method takes two arguments: the key and the value to store.

angular.module('myApp', [])
.controller('MyController', function($scope, $cacheFactory) {
var myCache = $cacheFactory('myCache');

// Storing some data in the cache
myCache.put('userData', { name: 'John Doe', age: 30 });
});

4. Retrieving Items from the Cache

You can retrieve the stored data using the get() method, passing in the key of the cached data.

angular.module('myApp', [])
.controller('MyController', function($scope, $cacheFactory) {
var myCache = $cacheFactory('myCache');

// Retrieve cached data
var cachedData = myCache.get('userData');
if (cachedData) {
console.log('Cached Data:', cachedData);
} else {
console.log('No cached data found.');
}
});

5. Removing Items from the Cache

If you want to remove a specific item from the cache, you can use the remove() method.

angular.module('myApp', [])
.controller('MyController', function($scope, $cacheFactory) {
var myCache = $cacheFactory('myCache');

// Removing a specific item from the cache
myCache.remove('userData');
});

6. Clearing the Entire Cache

To clear all data from the cache, you can use the removeAll() method. This will remove all items stored in that cache.

angular.module('myApp', [])
.controller('MyController', function($scope, $cacheFactory) {
var myCache = $cacheFactory('myCache');

// Clearing all items from the cache
myCache.removeAll();
});

7. Cache Information

To view information about the cache, such as the number of entries or the current size, you can use the info() method.

angular.module('myApp', [])
.controller('MyController', function($scope, $cacheFactory) {
var myCache = $cacheFactory('myCache');

// Storing data in the cache
myCache.put('userData', { name: 'John Doe', age: 30 });

// Retrieving cache information
var cacheInfo = myCache.info();
console.log('Cache Info:', cacheInfo);
});

Example: Using $cacheFactory with API Calls

A common use case for $cacheFactory is caching API responses. This can avoid repeated network requests and help in reducing loading times for frequently accessed data.

angular.module('myApp', [])
.service('ApiService', function($http, $cacheFactory) {
var apiCache = $cacheFactory('apiCache'); // Create a cache for API responses

this.getUserData = function(userId) {
// Check if the user data is already cached
var cachedData = apiCache.get(userId);
if (cachedData) {
return new Promise(function(resolve) {
resolve(cachedData); // Return cached data if available
});
}

// If data is not cached, make an HTTP request
return $http.get('https://api.example.com/users/' + userId)
.then(function(response) {
// Cache the API response
apiCache.put(userId, response.data);
return response.data;
});
};
})
.controller('MyController', function($scope, ApiService) {
$scope.loadUser = function(userId) {
ApiService.getUserData(userId).then(function(userData) {
$scope.user = userData;
});
};
});

In this example, the ApiService caches API responses in the apiCache cache. When the data for a user is requested, the service first checks if the data is already available in the cache. If not, it makes an HTTP request and stores the response in the cache.


Best Practices for Using $cacheFactory

  1. Limit Cache Size: By default, caches can grow indefinitely, consuming more memory as you store more data. You can set a capacity limit when creating a cache to automatically remove the oldest entries once the cache reaches the specified size. var myCache = $cacheFactory('myCache', { capacity: 50 });
  2. Use Cache for Expensive Operations: Use $cacheFactory to store results of expensive calculations or data fetches that are likely to be reused (e.g., API responses, computed values, etc.).
  3. Cache Clear on Changes: If the cached data is dependent on external factors (e.g., a user update), make sure to invalidate or clear the cache when those factors change.
  4. Persistence Considerations: Remember that $cacheFactory is only an in-memory cache. It will be cleared if the page is refreshed. If you need data persistence, consider using localStorage or sessionStorage.

Leave a Reply

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