Detailed explanation of angularjs custom cache use cases
This time I will bring you angularjs a detailed explanation of the custom cache usage cases, what are the precautions when using angularjs custom cache, the following is a practical case, let's take a look.
1. What is cache
#A cache is a component that can store data transparently so that it can be served faster in the future ask.
The more requests the cache can serve, the more overall system performance improves.
2. Caching in Angular
2.1 Introduction to $cacheFactory
$cacheFactory is a A service that generates cache objects for all Angular services. Internally, $cacheFactory creates a default cache object, even if we don't explicitly create one.
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 using the cache name via the get() method.
capacity: This capacity describes the maximum number of cache key-value pairs to be stored and saved using the cache at any given time.
2.2 Cache Object
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 cache object.
put(): The put() method allows us to put any key (string) in the form of a JavaScript object value into the cache. cache.put("hello","world");
put() method returns the value we put in the cache.
get(): The get() method allows us to access the cache value corresponding to a key. If the key is found, it returns its value; if 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 not found, it returns undefined . cache.remove("hello");
removeAll(): The removeAll() function is used to reset the cache and remove all cached values.
destory(): The destory() method is used to remove all references to the specified cache from the $cacheFactory cache registry.
3. Cache in $http
Angular’s $http service creates a cache with the ID $http. Making $http requests 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 particularly useful when the data does not change frequently. You can set it like this:
$http({ method: 'GET', url: '/api/users.json', cache: true //设置为true只是用来使用$http默认的缓存机制 });
Now, every request via $http to the URL /api/user.json will be stored in the default $http cache. The request key in this $http cache is the complete URL path.
If necessary, you can also operate this default $http cache (for example, if we initiate another request without cache to remind us that incremental changes have occurred, we can clear it in the default $http request this request).
In order to reference the default request of $http, just use the ID to get the cache through $cacheFactory():
var cache = $cacheFactory('$http');
For the cache under control, we can do all the processing when needed Normal operations, such as retrieving a cached response, clearing the entry from the cache, or eliminating all cached references.
// 获取上一次请求的缓存 var usersCache = cache.get('http://example.com/api.users.json'); // 删除上一次请求的缓存入口 cache.remove('http://example.com/api.users.json'); // 重新开始并移除全部缓存 cache.removeAll();
var cache = $cacheFactory.get('$http'); if(cache.get('cacheData')){ console.log(cache.get('cacheData')); }else{ helloService.play().then( function (data) { cache.put("cacheData", data); //往缓存中放入数据 console.log(data); } ); }
3.2 Custom cache
Sometimes it is possible to have more control over the cache and create rules for cache performance, which requires creating a new cache. Use $http request.
It's easy to make $http requests via a custom cache. Instead of passing a boolean parameter true to the request, you can pass the cache instance.
var myCache = $cacheFactory('myCache'); $http({ method: 'GET', utl: '/api/users.json', cache: myCache });
一个小demo:定义一个缓存服务,依赖注入到你要用的控制器中,直接使用
define([ 'angularModule' ],function(app){ app.factory('myCache', ['$cacheFactory', function($cacheFactory){ return $cacheFactory('myCache'); //自定义一个缓存服务 }]) });
//自定义缓存,有缓存就从缓存里取,否则就发送请求 if(myCache.get('cacheData')){ console.log(myCache.get('cacheData')); }else{ helloService.play(myCache).then( function (data) { myCache.put("cacheData", data); console.log(data); } ); } cache:只是为了可以使用默认$http的缓存机制 play : function (myCache) { return httpRequestService.request({ method : 'get', url : 'http://localhost:8080/hello/play', cache : myCache }) }
现在, $http 将会使用自定义的缓存而非默认缓存。
四、为 $http 设置默认缓存
每次我们想要发起一个 $http 请求时都要给它传递一个缓存实例并不方便,特别是对每个请求使用同一缓存的时候。
其实可以在模块的 .config() 方法中通过 $httpProvider 设置 $http 默认使用的缓存对象。
angular.module('myApp', []).config(function($httpProvider) { $httpProvider.defaults.cache = $cacheFactory('myCache', {capacity: 20}); });
这个 $http 服务不再使用它为我们创建的默认缓存;它会使用我们自定义的缓存,实际上这就是一个近期缓存最久未使用算法① (Least Recently Used,LRU)。
LRU缓存根据缓存容量只保留最新的缓存数目。也就是说,我们的缓存容量为20,因此会缓存前20个请求,但是进入第21个请求时,最近最少使用的请求条目就会从缓存中被删除。这个缓存自身会负责具体哪些要维护,哪些要移除。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed explanation of angularjs custom cache use cases. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



An avatar on Netflix is a visual representation of your streaming identity. Users can go beyond the default avatar to express their personality. Continue reading this article to learn how to set a custom profile picture in the Netflix app. How to quickly set a custom avatar in Netflix In Netflix, there is no built-in feature to set a profile picture. However, you can do this by installing the Netflix extension on your browser. First, install a custom profile picture for the Netflix extension on your browser. You can buy it in the Chrome store. After installing the extension, open Netflix on your browser and log into your account. Navigate to your profile in the upper right corner and click

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

How to customize shortcut key settings in Eclipse? As a developer, mastering shortcut keys is one of the keys to improving efficiency when coding in Eclipse. As a powerful integrated development environment, Eclipse not only provides many default shortcut keys, but also allows users to customize them according to their own preferences. This article will introduce how to customize shortcut key settings in Eclipse and give specific code examples. Open Eclipse First, open Eclipse and enter

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

1. The picture below is the default screen layout of edius. The default EDIUS window layout is a horizontal layout. Therefore, in a single-monitor environment, many windows overlap and the preview window is in single-window mode. 2. You can enable [Dual Window Mode] through the [View] menu bar to make the preview window display the playback window and recording window at the same time. 3. You can restore the default screen layout through [View menu bar>Window Layout>General]. In addition, you can also customize the layout that suits you and save it as a commonly used screen layout: drag the window to a layout that suits you, then click [View > Window Layout > Save Current Layout > New], and in the pop-up [Save Current Layout] Layout] enter the layout name in the small window and click OK

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

In an excel table, sometimes you may need to insert coordinate axes to see the changing trend of the data more intuitively. Some friends still don’t know how to insert coordinate axes in the table. Next, I will share with you how to customize the coordinate axis scale in Excel. Coordinate axis insertion method: 1. In the excel interface, select the data. 2. In the insertion interface, click to insert a column chart or bar chart. 3. In the expanded interface, select the graphic type. 4. In the right-click interface of the table, click Select Data. 5. In the expanded interface, you can customize it.
