SoFunction
Updated on 2025-04-12

Detailed explanation of the use of angularjs cache

1. What is cache

A cache is a component that can store data transparently so that requests can be served faster in the future.

The more requests the cache can serve, the more the overall system performance will be improved.

2. Cache in Angular

2.1 Introduction to $cacheFactory

$cacheFactory is a service that generates cache objects for all Angular services. Internally, $cacheFactory creates a default cache object, even if we don't create it displayed.

To create a cache object, you can use $cacheFactory to create a cache with an ID:

var cache = $cacheFactory('myCache');
This $cacheFactory method can accept two parameters:

cacheId (string): This cacheId is the ID name when creating the cache. It can be referenced by the get() method using the cache name.

capacity: This capacity describes the maximum number of cache key-value pairs to be stored and saved at any given time.

2.2 Cache Objects

The cache object itself has the following methods that can be used to interact with the cache.

info(): The info() method returns the ID, size and options of the cached object.

put() : The put() method allows us to put keys (strings) in the form of arbitrary JavaScript object values ​​into the cache. ("hello","world");

The put() method returns the value we put into the cache.

get() : The get() method allows us to access the cached value corresponding to a key. If this key is found, it returns its value; if not found, it returns undefined. ("hello");

remove() : The remove() function is used to remove a key-value pair from the cache if it is found. If not found, it returns undefined . ("hello");

removeAll() : The removeAll() function is used to reset the cache while removing all cached values.

destory() : The destory() method is used to remove all references from the $cacheFactory cache registry.

3. Cache in $http

Angular's $http service creates a cache with an ID of $http. To make the $http request use the default cache object is simple: The $http() method allows us to pass it a cache parameter.

3.1 Default $http cache

The default $http cache is especially useful when the data does not change frequently. It can be set like this:

$http({
  method: 'GET',
  url: '/api/',
  cache: true//Setting true is just used to use the default cache mechanism of $http});

Now, each request through $http to URL /api/ will be stored in the default $http cache. The request key in the $http cache is the complete URL path.

If necessary, you can also operate the default $http cache (for example, if another uncached request we initiate reminds us that there has been an incremental change, we can clear the request in the default $http request).

To reference the default request for $http, just use the ID via $cacheFactory() to get the cache:

var cache = $cacheFactory('$http');

For the cache under control, we can do all normal operations when needed, such as retrieving cached responses, clearing entries from the cache, or eliminating all cached references.

// Get the cache of the last requestvar usersCache = ('/');
// Delete the cache entry of the last request('/');
// Start again and remove all caches();
    var cache = $('$http');
    if(('cacheData')){
      (('cacheData'));
    }else{
      ().then(
        function (data) {
          ("cacheData", data);//Put data into the cache          (data);
        }
      );
    }

3.2 Custom cache

Sometimes there is more control over the cache and create rules for the cache performance, which requires creating a new cache to use the $http request.

It is easy to make a $http request initiated by a custom cache. You can pass cache instances without having to pass a boolean parameter true to the request.

var myCache = $cacheFactory('myCache');
$http({
method: 'GET',
utl: '/api/',
cache: myCache
});

A small demo: defines a cache service, injects dependencies into the controller you want to use, and directly use it

define([
  'angularModule'
],function(app){
  ('myCache', ['$cacheFactory', function($cacheFactory){
    return $cacheFactory('myCache'); //Customize a cache service  }])
});
    //Custom cache, if there is a cache, get it from the cache, otherwise the request will be sent    if(('cacheData')){
      (('cacheData'));
    }else{
      (myCache).then(
        function (data) {
          ("cacheData", data);
          (data);
        }
      );
    }
      cache:Just to use the default$httpCache mechanism
      play : function (myCache) {
        return ({
          method : 'get',
          url : 'http://localhost:8080/hello/play',
          cache : myCache
        })
      }

Now $http will use a custom cache instead of a default cache.

4. Set default cache for $http

It is not convenient to pass a cache instance to a $http request every time we want to initiate a $http request, especially when using the same cache for each request.

In fact, you can set the cache object used by $http by default in the module's .config() method.

('myApp', []).config(function($httpProvider) {
$ = $cacheFactory('myCache', {capacity: 20});
});

The $http service no longer uses the default cache it creates for us; it uses our customized cache, which is actually a algorithm that has not been used recently (Least Recently Used, LRU).

The LRU cache only retains the latest cache number according to the cache capacity. That is, our cache capacity is 20, so the first 20 requests will be cached, but when we enter the 21st request, the least recently used request entry will be deleted from the cache. This cache itself will be responsible for the specific maintenance and removal of which ones.

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.