Given a Ajax request in AngularJS
$http.get("/backend/").success(callback);
what is the most effective way to cancel that request if another request is launched (same backend, different parameters for instance).
Given a Ajax request in AngularJS
$http.get("/backend/").success(callback);
what is the most effective way to cancel that request if another request is launched (same backend, different parameters for instance).
here is a version that handles multiple requests, also checks for cancelled status in callback to suppress errors in error block. (in Typescript)
controller level:
in my http get:
helper methods
now looking at the network tab, i see that it works beatuifully. i called the method 4 times and only the last one went through.
If you want to cancel pending requests on stateChangeStart with ui-router, you can use something like this:
// in service
// in UIrouter config
You can add a custom function to the
$http
service using a "decorator" that would add theabort()
function to your promises.Here's some working code:
This code uses angularjs's decorator functionality to add a
with_abort()
function to the$http
service.with_abort()
uses$http
timeout option that allows you to abort an http request.The returned promise is modified to include an
abort()
function. It also has code to make sure that theabort()
works even if you chain promises.Here is an example of how you would use it:
By default when you call
abort()
the request gets canceled and none of the promise handlers run.If you want your error handlers to be called pass true to
abort(true)
.In your error handler you can check if the "error" was due to an "abort" by checking the
xhrStatus
property. Here's an example:This feature was added to the 1.1.5 release via a timeout parameter:
Cancelation of requests issued with
$http
is not supported with the current version of AngularJS. There is a pull request opened to add this capability but this PR wasn't reviewed yet so it is not clear if its going to make it into AngularJS core.This enhances the accepted answer by decorating the $http service with an abort method as follows ...
WHAT IS THIS CODE DOING?
To cancel a request a "promise" timeout must be set. If no timeout is set on the HTTP request then the code adds a "promise" timeout. (If a timeout is set already then nothing is changed).
However, to resolve the promise we need a handle on the "deferred". We thus use a map so we can retrieve the "deferred" later. When we call the abort method, the "deferred" is retrieved from the map and then we call the resolve method to cancel the http request.
Hope this helps someone.
LIMITATIONS
Currently this only works for $http.get but you can add code for $http.post and so on
HOW TO USE ...
You can then use it, for example, on state change, as follows ...