Let’s talk about cache first:
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 introduction:
$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.
1. The role of $cacheFactory in Angular:
Used to generate a service to store cached objects and provide access to the objects.
2. The method of $cacheFactory in Angular:
(1) put(key,value);
Insert a key value pair (key,value) into the cache object.
(2) get(key);
Get the corresponding value by specifying the key in the cache object.
(3) romove(key);
Delete the corresponding value in the cache object by specifying the key.
(4) removeAll();
Delete all key-value pairs in the cache object.
(5) destroy();
Destroy this cache object.
(6) info();
Get cache object information (id, size).
Note: key: string type, value name in cache object.
value: All types, cache the value in the object.
3. Usage of $cacheFactory in Angular:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>Cache Example</title> <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script> </head> <body ng-app="app"> <div ng-controller="myCtrl1" ></div> <div ng-controller="myCtrl2" ></div> <div></div> <script type="text/javascript"> var app=angular.module("app",[]); app.controller('myCtrl1',['$scope','$cacheFactory',function($scope,$cacheFactory){ var cache = $cacheFactory('cache01'); cache.put('name','Zhang San'); cache.put('age',18); var info = cache.info(); console.log(info); }]); app.controller('myCtrl2',['$scope','$cacheFactory',function($scope,$cacheFactory){ var cache = $cacheFactory.get('cache01'); var name = cache.get('name'); console.log(name); }]); </script>result:
The above is a detailed explanation of the role and usage examples of $cacheFactory in Angular introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!