简体   繁体   中英

How to make http request in my case

I am trying to prevent multiple http requests being fired in my codes.

I have something like

in my controller

//if use click, fire this method
var getItems = function() {
    factory.makeRequest.then(function(data){
        //do stuff with data...
    })
}

in my 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 will prevent the request being fired multiple time if the process is on going. However, I get Cannot read property of .then of 'undefined' if I click the button again before the promise is resolved. I know it's because the $http request doesn't return anything as I have $http.pendingRequests.length===0 condition. The above codes give me what I need but I don't know how to prevent the error in console log. Can anyone help me out? thanks a lot!

The following will return the current request promise, if it exists, otherwise it will create a new request and return that promise. It will clean up the 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM