Skip to content

Instantly share code, notes, and snippets.

@benoitboucart
Last active September 20, 2017 18:31
Show Gist options
  • Save benoitboucart/8810514 to your computer and use it in GitHub Desktop.
Save benoitboucart/8810514 to your computer and use it in GitHub Desktop.
Limit the number of requests with batch requests in AngularJS
// Going mobile with Angular by Ari
// Limit & batch number of network requests
// Source: https://speakerdeck.com/auser/going-mobile-with-angular?utm_source=ng-newsletter&utm_campaign=b5794c7e19-AngularJS_Newsletter_2_4_142_3_2014&utm_medium=email&utm_term=0_fa61364f13-b5794c7e19-96511737
angular.module('myApp.services')
.factory('NetworkBatcher', function($http){
var service = {
promises: [],
addCall: function(obj){
var promise = $http(obj);
service.promises.push(promise);
return promise;
},
runAll: function(){
return $q.all(service.promises);
}
};
return service;
});
// Usage
angular.module('myApp.services')
.factory('Account', function(NetworkBatcher){
return {
getAccounts: function(){
return NetworkBatcher.addCall({method: 'GET', url: '/v1/accounts.json')});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment