Cache usage in AngularJS

  • 2021-07-10 18:35:12
  • OfStack

Cache article

A cache is a component that stores data transparently so that requests can be serviced more quickly in the future. Obtaining resources repeatedly may lead to duplication of data and consume time. Therefore, the cache is suitable for 1 data with little variability. The more requests the cache can serve, the more the overall system performance can be improved.

$cacheFactory and Cache Objects

$cacheFactory is a service that produces cache objects for the Angular service. To create 1 cache object, use $cacheFactory over 1 ID and 1 capacity. Where ID is the name of a cache object and capacity is the maximum number of cache key-value pairs. To give a vivid example, $cacheFactory is a renter. She has a building with large and small houses to rent. As long as you give enough money, the renter will rent the house to you (get cached objects). This house includes its room number (ID) and room size (capacity-capacity).


var myCache = $cacheFactory('myCache');

Among them, cache objects have the following methods

1. myCache. info () Returns the ID, size, and options of the cached object

2. myCache. put () New value key-value pair and put into cache object myCache. put ("name", "Ben")

3. myCache. get () returns the corresponding cache value, if not found, undefined myCache. get ("name")

4. myCache. remove () Removes the key-value pair from the corresponding cache object myCache. remove ("name")

5. myCache. remvoeAll () empties the cache object

Cache in $http

The $http () method allows us to pass one cache parameter. The default $http cache is especially useful when data does not change very often. Where the default $http cache object is var cache = $cacheFactory ('$http'); You can set it like this


$http({
   method: 'GET',
   url: 'api/user.json',
   cache: true
})

Where the cached key values are url, var userCache = cache. get ('api/user. json')

Custom cache

Getting $http to initiate a request through a custom cache is also simple, simply setting the cache value to the corresponding cache object name


$http({
   method: 'GET',
   url: 'api/user.json',
   cache: myCache
})

Or set the cache object for each $http request through config configuration, instead of adding configuration to every 1 $http request as in the above example


app.config(function($httpProvider){
$httpProvider.defaults.cache = $cacheFactory('myCache',{capacity: 20})

Among them, capacity will use the "recent cache longest unused algorithm", that is to say, if the cache capacity is 20, 20 caches have been cached now. When the 21st cache wants to be cached, the longest and smallest unused cache key value pair will be cleared to make room for the 21st cache.


Related articles: