简体   繁体   中英

Canceling HTTP request and resolving error function in angular

Hi I want to cancel my http request after 2s. 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. Where do I use the $timeout exactly? 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(function(){
    return canceler.reject(reason);
},2000);

So, you $http request look like :

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(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.

So an example for your POST method invocation will be:

$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

On the other hand, the $timeout is an Angular's wrapper for window.setTimeout here is the link for the documentation .

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. That would depend on your requirement. But my recommendation is to use the timeout property for the request that your are doing. There is no need to cancel the request by an external timer.

You can use $timeout to achieve this. You cancel the http request or the timeout promise according to which one ends first. If timeout occurs first you cancel http request, if http promise resolves before timeout you cancel timeout. 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;
});

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