$http is a core service in AngularJS, used to read data from remote servers. In actual AngularJS projects, it is often necessary to process multiple $http requests. Each $http request returns a promise. We can put multiple promises into an array argument accepted by the $q.all() method.
1. Handle 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 formal parameter of the get method of $http accepts an object. The cache field of the object can accept a bool type to implement caching, that is, {cache:true}, or it can also accept a service.
Create a service through factory method 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"); } })
Editor’s summary:
● In fact, it is $cacheFactory
that implements the caching mechanism
● Place the caching mechanism in the current request through {cache:myCache}
● $cacheFactory uses the request api as the key, so when clearing the cache, it also clears the cache based on this key
The above is the method of $http caching and processing multiple $http requests in AngularJS shared by the editor. I hope it will be helpful to everyone.