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
what is the most effective way to cancel that request if another request is launched (same backend, different parameters for instance). |
||||
|
This feature was added to the 1.1.5 release via a timeout parameter:
|
|||||||||||||||||||||
|
Cancelation of requests issued with |
|||||||||||||||||
|
Cancelling Angular $http Ajax with the timeout property doesn't work in Angular 1.3.15. For those that cannot wait for this to be fixed I'm sharing a jQuery Ajax solution wrapped in Angular. The solution involves two services:
Here goes the PendingRequestsService service:
The HttpService service:
Later in your service when you are loading data you would use the HttpService instead of $http:
Later in your code you would like to load the data:
|
|||
|
If you want to cancel pending requests on stateChangeStart with ui-router, you can use something like this: // in service
// in UIrouter config
|
|||||
|
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 ...
|
|||||||||||||||||
|