简体   繁体   English

取消HTTP请求并解决angular中的错误功能

[英]Canceling HTTP request and resolving error function in angular

Hi I want to cancel my http request after 2s. 嗨,我想在2秒后取消我的http请求。 If no data was received it should resolve into the error function and return an empty object. 如果未接收到数据,则应解析为错误函数并返回一个空对象。

I know I somehow have to use the timeout property. 我知道我必须以某种方式使用timeout属性。 Where do I use the $timeout exactly? 我在哪里确切使用$ timeout? I am not so sure if I understood it correctly. 我不确定我是否理解正确。

app
  .service('testService',['$http','$q','$timeout',
    function($http,$q,$timeout){

      var canceler=$q.defer();

      this.options = function (long,lat) {


        return $http({
          method: 'POST',
          url: '/coordinates',
          headers: {
            'Content-Type' : 'application/json; charset=utf-8',
            'Data-Type': 'json'
          },
          data: {
            "long":long,
            "lat": lat
          },
          timeout:canceler.promise

        }).then(function (response) {
          return response.data;
        },function(error){
          return {};
        });
      };
    }]);

Use reject in your $timeout as 在$ timeout中使用reject

$timeout(function(){
    return canceler.reject(reason);
},2000);

So, you $http request look like : 因此,您的$http请求看起来像:

var timeoutCase = function(){
    $timeout(function(){
        return canceler.reject(reason);
    },2000);
}

var apiCall = function(){

   // call timeout function
   timeoutCase();

   // http call
   return $http({
      method: 'POST',
      url: '/coordinates',
      headers: {
        'Content-Type' : 'application/json; charset=utf-8',
        'Data-Type': 'json'
      },
      data: {
        "long":long,
        "lat": lat
      },
      timeout:canceler.promise

    }).then(function (response) {
$timeout.cancel(timeoutCase);
      return response.data;
    },function(error){
      return {};
    });
}

// call Http function.
api().then(function(response){
    console.log(response);
})

You can pass a configuration object to the method that your are using (In your scenario POST): 您可以将配置对象传递给正在使用的方法(在场景POST中):

post(url, data, [config]);

In the config object you can specify a timeout property: 在配置对象中,您可以指定超时属性:

timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved. 超时– {number | Promise} –超时(以毫秒为单位),或承诺应在解决后中止请求。

So an example for your POST method invocation will be: 因此,您的POST方法调用的示例将是:

$http.post('www.host.com/api/resource', {payload}, {timeout:2000})
          .then(function(){ //success });
          .catch(function(){ return {};});

return {}; Is just to simulate the empty object that you mention. 只是为了模拟您提到的空对象。

On the angular documentation site there are some good examples of using the $http service 在angular文档站点上,有一些使用$ http服务的很好的例子。

On the other hand, the $timeout is an Angular's wrapper for window.setTimeout here is the link for the documentation . 另一方面, $timeout是Angular的window.setTimeout的包装器,这里是文档的链接。

So you could use the $timeout to trigger resolve your canceler promise, or just let the timeout property do it's job while doing the request. 因此,您可以使用$ timeout触发解决您的取消承诺,或者只是让timeout属性在执行请求时完成它的工作。 That would depend on your requirement. 那将取决于您的要求。 But my recommendation is to use the timeout property for the request that your are doing. 但是我的建议是对您正在执行的请求使用timeout属性。 There is no need to cancel the request by an external timer. 无需通过外部计时器取消请求。

You can use $timeout to achieve this. 您可以使用$ timeout实现此目的。 You cancel the http request or the timeout promise according to which one ends first. 您取消http请求或超时承诺,以先终止为准。 If timeout occurs first you cancel http request, if http promise resolves before timeout you cancel timeout. 如果首先发生超时,则您取消http请求,如果http承诺在超时之前解析,则取消超时。 Here is an example: 这是一个例子:

var httpPromise = $http({
          method: 'POST',
          url: '/coordinates',
          headers: {
            'Content-Type' : 'application/json; charset=utf-8',
            'Data-Type': 'json'
          },
          data: {
            "long":long,
            "lat": lat
          }
        });

var timeoutPromise = $timeout(function () {
      httpPromise.reject("Timeout occurred"); // timeout occurred first, reject httpPromise.
}, 2000);

return httpPromise.then(function(data){
   $timeout.cancel(timeoutPromise); //http request resolved before timeout occurred, cancel the timeout.
   return data;
});

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

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