javascript - How to make http request in my case -
i trying prevent multiple http requests being fired in codes.
i have like
in controller
//if use click, fire method var getitems = function() { factory.makerequest.then(function(data){ //do stuff data... }) }
in factory
var factory = {}; factory.makerequest = function(){ if($http.pendingrequests.length===0) { return getdata() .then(function(data) { //do stuff here return data; }) } } factory.getdata = function() { return $http.get('/project/item'); } return factory;
the above code prevent request being fired multiple time if process on going. however, cannot read property of .then of 'undefined'
if click button again before promise resolved. know it's because $http
request doesn't return have $http.pendingrequests.length===0
condition. above codes give me need don't know how prevent error in console log. can me out? lot!
the following return current request promise, if exists, otherwise create new request , return promise. clean current request on success.
var factory = {}; factory._currentrequest = null; factory.makerequest = function(){ if(!factory._currentrequest) { factory._currentrequest = factory.getdata() .then(function(data) { //do stuff here factory._currentrequest = null; return data; }) } return factory._currentrequest } factory.getdata = function() { return $http.get('/project/item'); } return factory;