Cancel AngularJS $http Requests

April 13, 2017 by Chris Sherman

Requests made with the AngularJS $http service execute asynchronously. In certain situations, we may want to avoid executing the request’s success callback function and effectively cancel the request.

In the $http service docs, you’ll find a timeout configuration property. According to the docs, this property represents a “timeout in milliseconds, or promise that should abort the request when resolved.”

Usage

With the timeout configuration hook, we’ll create a promise with the $q service and resolve it to cancel the request. In the plunker example below, you can click a button to that initates a request and immediately cancels it. We know the request was cancelled because it will return a status code of -1. To demonstrate the difference, you can use the other button to initiate a request that will result in a status code of 404.

Generally we will not immediately cancel the request, but rather use the reference to the httpRequestCanceller in the controller to cancel the request in response to an event or user input. You can find an example of cancelling in-process requests in the activate function of the app.js controller of the plunker above. The example shows cancelling a request in response to a broadcast event, but we can just as easily bind the cancelRequestOnBroadcastEvent function to a click or mouse event.

AngularJS