Angular Js Caching – $cacheFactory

Cache

A cache used to store and retrieve data, mainly used by $http to cache templates and other data.

Cache data does not need to be recomputed, whereas fetching new data would result in duplicated data.

Cache works as a key-value pair. There is s a key which points to a cached content.
If the key is found in the cache.

Angular js offers caching feature for built in services and it gives us the ability to use the same mechanisms to cache our custom content.

Here, I’ll discuss about caching strategies in Angular.

 

$cacheFactory

The $cacheFactory is the service that generates cache objects for Angular services. Internally, the $cacheFactory creates a default cache object.

$cacheFactory is small and useful.

To create a cache object, we use the $cacheFactory and create a cache by ID:
var cache = $cacheFactory(‘myCache’);

$cacheFactory() method returns a cache object.

 

Caching using $http

Angular’s $http service creates a cache with the ID $http. To Enable the $http request to use this default cache object is simple.

The $http method allow us to pass a cache parameter.

 

Default $http Cache

The default $http cache is useful when data does not change very often.

$http({
   method: 'GET',
   url: '/api/user-list',
   cache: true
});
// Or, using the get

$http.get('/api/user-list', {
   cache: true
});

Every request is made through $http to the URL ‘/api/user-list’ will be stored in the default $http cache.

The key for this request in the $http cache is the full-path URL.

var cache = $cacheFactory.get(‘$http’);
we can do all the operations, such as retrieve the cached responses, clear data from the cache.

// Get cache for the previous request
var userList = cache.get(‘http://www.nitishkumarsingh.com/api/user-list’);

// To Delete the cache for the previous request
cache.remove(‘http://www.nitishkumarsingh.com/api/user-list’);

// To Remove all cache
cache.removeAll();

 

We can also create custom cache instead of passing a boolean true with the request.
we can pass the instance of the cache.

var cache = $cacheFactory.get('cache');
$http({
   method: 'GET',
   url: '/api/user-list',
   cache: cache
});
// Or, using the get
$http.get('/api/user-list', {
   cache: cache
});

For More Information Visit:

https://www.ng-book.com/p/Caching/

https://docs.angularjs.org/api/ng/service/$cacheFactory

https://docs.angularjs.org/api/ng/type/$cacheFactory.Cache