Divya MV
Divya MV

Reputation: 2053

AngularJS: How to Abort a http request that i have not yet received the response

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.

Upvotes: 2

Views: 953

Answers (2)

frhd
frhd

Reputation: 10244

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'

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691635

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");

Upvotes: 4

Related Questions