$ Http is a core service in AngularJS. It is used to read data from remote servers. This article describes $ http cache and how to process multiple $ http requests in AngularJS, hope you can learn it together. $ http is a core service in AngularJS and is used to read data from remote servers. In actual AngularJS projects, you often need to process multiple $ http requests. Each $ http request returns a promise. We can put multiple promise into $ q. the all () method accepts an array of arguments.
1. process multiple $ http requests
angular.module('app',[]).controller('AppCtrl', function AppCtrl(myService){var app = this;myService.getAll().then(function(info){app.myInfo = info;})}).service('myService', function MyService($http, $q){var myService = this;user = 'https://api...',repos = '',events = '';myService.getData = function getData(){return $http.get(user).then(function(userData){return {name:userData.data.name,url:userData.data.url,repoCount: userData.data.count}})};myService.getUserRepos = function getUserRepos(){return $http.get(repos).then(function(response){return _.map(response.data, function(item){return {name: item.name,description:item.description,starts: item.startCount}})})}myService.getUserEvents = function getUserEvents(){...}myService.getAll = function(){var userPromise = myService.getData(),userEventsPromise = myService.getUserRepos(),userReposPromise = myService.getUserRepos();return $q.all([userPromise, userEventsPromise, userReposPromise]).then(function(){....})}})
2. $ http request Cache
$ The second parameter of the http get method accepts an object. The cache field of this object can accept a bool-type implementation cache, that is, {cache: true}. It can also accept a service.
Create a service in the factory mode and inject the service into the controller.
angular.module('app',[]).factory("myCache", function($cacheFactory){return $cacheFactory("me");}).controller("AppCtrl", function($http, myCache){var app = this;app.load = function(){$http.get("apiurl",{cache:myCache}).success(function(data){app.data = data;})}app.clearCache = function(){myCache.remove("apiurl");}})
Summary:
● In fact, the cache mechanism is $ cacheFactory.
● Put the cache mechanism in the current request through {cache: myCache}
● $ CacheFactory uses the request api as the key. Therefore, when the cache is clear, the cache is cleared based on the key.
The above section describes the $ http cache in AngularJS and the method for handling multiple $ http requests. I hope this will help you.