ABORT! ABORT! ABORT! Cancelling $http calls

Whilst working on a project, I got to a point where the user may need to request up to date data from the server. The data request itself is made using Angular’s $http object. However, depending on circumstances, before the data is returned the user may then need to leave that screen / activity and forget about the data request. The problem is, the user may forget about that request, but the callback methods registered with the $http call certainly won’t. Now depending on your application, when the relevant callback is triggered the user may experience some unwanted activity.

“Promises, promises”
If we take a look at the anatomy of a very simple $http request we can see there is the $http call itself and two $http specific methods which are called depending on the outcome of the http request (NB since this article is geared towards aborting a http call, I won’t go into which http status codes trigger which method).

According to the AngularJS documentation, a $http GET or POST can be passed an optional ‘config’ object which (amongst other things) has the following property:

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


This means when setting up out $http request, we can provide a promise as the ‘timeout’ value and should we need to abort the $http call we can simply resolve the promise.

“Make it so”
As a simple example we can do something like this in our controller:

And your request will be cancelled.

Now this is fine for a contrived, closed-loop blog example, but what about the real world? It’s more than likely that you will want to keep track of multiple requests, and to further complicate things, you may want to cancel some and not others.
One way to achieve this (I’m sure there’s a million other ways) is to create a factory to act as a service wrapper around the $http calls allowing us to manage the returned promise.

Below is a plunk to demonstrate this technique. If you hit “Get Data” a request is added to the list and you will have a (limited) opportunity to cancel the $http request but hitting the “Cancel” button.:

Then in the “Network” section of your browsers you will be able to see the request being aborted:
abort Happy coding!

– Jonathan