2

What i am trying to do is to cancel a request or stop listening for the response for a particular request . i cannot use a timeout in the request.the decision of whether to cancel or not is done only after the request is made .I have seen solutions in ajax jQuery as found in this. Is there any angular solutions for the same.i am using $http for making POST requests.

Community
  • 1
  • 1
Divya MV
  • 2,021
  • 3
  • 31
  • 55
  • have you tried using request interceptors ? https://docs.angularjs.org/api/ng/service/$http – svarog May 04 '15 at 06:33

2 Answers2

4

This is described in the documentation:

timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.

So, when sending the request, pass a promise to the configuration timeout, and resolve it when you decide to abort:

var cancelDefer = $q.defer();
$http.get(url, {
    timeout: cancelDefer.promise
}).success(...);

// later, to cancel the request:
cancelDefer.resolve("cancelled");
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • May i know which angular version supports the promise object in timeout.I am using v1.2.26 – Divya MV May 04 '15 at 06:44
  • 1
    Sure: go to the documentation page, make sure to select the version 1.2.26 in the upper-left corner, and see if that version supports it. – JB Nizet May 04 '15 at 06:47
0

Just to add a coffeescript version I've used recently:

canceller = $q.defer()

$http.get (requestUrl, { timeout: canceller.promise })
  .then (response) ->
    $scope.remoteData = response.data;

$scope.cancel = () ->
  canceller.resolve 'Cancelled http request'
frhd
  • 9,396
  • 5
  • 24
  • 41