Cache
A cache is a component that can store data transparently so that it can serve requests faster in the future. Retrieving resources repeatedly may cause data duplication and consume time. Therefore, cache is suitable for some data that is not very variable. 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 Angular services. To create a cache object, you can use $cacheFactory to pass an ID and capacity. Among them, ID is the name of a cache object, and capacity is the maximum number of cached key-value pairs. To give a vivid example, $cacheFactory is a landlord. She has a building where houses of all sizes can be rented. As long as you give enough money, the landlord will rent the house to you (get the cache object). This house includes its house number (ID) and room size (capacity-capacity).
var myCache = $cacheFactory('myCache');
Among them, the cache object has the following methods
1. () Returns the ID, size and options of the cached object
2. () New value key-value pairs and put them into the cache object ("name", "Ben")
3. () Returns the corresponding cache value, if not found, it returns undefined ("name")
4. () Remove key-value pairs from the corresponding cache object ("name")
5. () Clear the cache object
Cache in $http
The $http() method allows us to pass a cache parameter. The default $http cache is especially useful when the data does not change frequently. Where, the default $http cache object is var cache = $cacheFactory('$http'); it can be set like this
$http({ method: 'GET', url: 'api/', cache: true })
where the cached key value is url, var userCache = ('api/')
Custom cache
It is also very simple to make $http initiate requests through custom cache. Just set the cache value to the corresponding cache object name.
$http({ method: 'GET', url: 'api/', cache: myCache })
Or use config to set the cache object for each $http request, without adding configuration to each $http request like in the above example.
(function($httpProvider){ $ = $cacheFactory('myCache',{capacity: 20})
Among them, capacity will use the "recent cache longest unused algorithm", that is, if the cache capacity is 20, 20 caches have been cached. When the 21st wants to be cached, the longest and least unused cache key-value pair will be cleared to free up space to accommodate the 21st cache.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.