简体   繁体   English

在我的情况下如何发出HTTP请求

[英]How to make http request in my case

I am trying to prevent multiple http requests being fired in my codes. 我试图防止在我的代码中触发多个http请求。

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. 但是,如果我在解决承诺之前再次单击该按钮,则会得到Cannot read property of .then of 'undefined' I know it's because the $http request doesn't return anything as I have $http.pendingRequests.length===0 condition. 我知道这是因为$http请求没有返回任何内容,因为我有$http.pendingRequests.length===0条件。 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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