Angularjs Cache Explanation

Source: Internet
Author: User
Tags delete cache

First, what is the cache

A cache is a component that transparently stores data so that it can serve requests more quickly in the future.

The more requests the cache can serve, the more overall system performance is raised.

Second, the cache in the Angular

2.1 $cacheFactory Introduction

$cacheFactory is a service that generates cache objects for all angular services. Internally, $cacheFactory creates a default cache object, even if we do not create it in the display.

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 the cache is created. You can use the cache name to refer to it by using the Get () method.

Capacity: This capacity describes the maximum number of cache key-value pairs to use for cache storage 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 a key (string) in the form of any JavaScript object value into the cache. Cache.put ("Hello", "World");
The put () method returns the value that we put in the cache.
Get (): Get () method allows us to access the cache value corresponding to a key. If the key is found, it returns its value, and if it is not found, it returns undefined. Cache.get ("Hello");
Remove (): the Remove () function is used to remove a key-value pair from the cache if it is found. If it is not found, it will return to undefined. Cache.remove ("Hello");
RemoveAll (): the RemoveAll () function resets the cache and removes all cached values.
Destory (): The Destory () method removes all references to the specified cache from the $cacheFactory cache registry.

Iii. Caching in the $http

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

3.1 Default $http Cache
The default $http cache is especially useful when the data does not change frequently. You can set it like this:

$http ({    ' GET ',    '/api/users.json ',    true//set to True just to use $http default caching mechanism });

Each request that passes $http to Url/api/user.json is now stored in the default $http cache. The request key in this $http cache is the full URL path.

If necessary, you can also manipulate this default $http cache (for example, if another request we initiated that does not have a cache reminds us that an incremental change has occurred, we can clear the request in the default $http request).

  var  cache = $cacheFactory (' $http '  For a controlled cache, we can do all the normal things we need to do, such as retrieving cached responses, purging entries from the cache, or eliminating all cached references.  //  get cache of last request   var  userscache = cache.get (' Http://example.com/api.users.json '  //  Delete cache entry for last request  Cache.remove (' Http://example.com/api.users.json ' 
        var cache = $cacheFactory. Get (' $http ');         if (Cache.get (' CacheData ')) {            console.log (' Cache.get (' CacheData '));        } Else {            helloservice.play (). Then (                function  (data) {                    cache.put ("  CacheData ", data); //Put data                    in cache Console.log (data);                }            );        }

3.2 Custom Cache

Sometimes it is possible to have more control over the cache and create rules for the performance of the cache, which requires creating a new cache to use $http requests.

It is easy to make requests from $http by customizing the cache. You can adopt a method of passing a cache instance without having to pass a Boolean parameter true to the request.

var mycache = $cacheFactory (' mycache 'GET '/api/users.json ', Cache:mycache});

A small demo: Define a caching service that is injected into the controller you want to use, directly using

define ([   ' Angularmodule '],function(APP) {    app.factory (function  ($cacheFactory) {        return $cacheFactory (' Mycache ');  // Customizing a cache service     }])});
 //  custom cache, with cache taken from cache, or send request  
   
    if  (Mycache.get (' CacheData ' 
     ' cachedata '  else  {helloservice.play (Mycache). Then (                     function   "CacheData" 
   
            cache: Just to be able to use the default $http caching mechanism            function (mycache) {                return  httprequestservice.request ({                    ' get ',                    '/http/ Localhost:8080/hello/play ',                    cache:mycache                })            }

$http will now use the custom cache instead of the default cache.

Iv. Setting the default cache for $http

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

In fact, you can set $http cache object by default in the. config () method of the module by using the $httpProvider.

Angular.module (' myApp ', []). config (function= $cacheFactory (' Mycache ', {capacity:20});});

This $http service no longer uses the default cache it created for us; it uses our custom cache, which is actually the longest unused algorithm ① (Least recently USED,LRU) in a recent cache.

The LRU cache retains only the latest number of caches based on the cache capacity. That is, our cache capacity is 20, so the first 20 requests are cached, but when we enter the 21st request, the least recently used request entries are removed from the cache. The cache itself is responsible for what to maintain and what to remove.

Angularjs Cache Explanation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.