Cancel $http requests in AngularJS

Recently i came across a situation where i needed to cancel $http requests in Angular. At first glance at the issue, i thought i did not have control over the requests that are sent, however after some research came to the conclusion that we can cancel $http requests. The following is what i did:

Example 1 – Normal jQuery – Ajax

Keep a reference to the request as follows:

var xhr = $.ajax({
    type: "POST",
    url: "user.php",
    data: "fname=Roy&lname=MJ",
    success: function(result) {
        alert("Success: " + result);
    },
    error: function(err) {
        alert("Error: " + err);
    }
});

Now you can simple cancel $http requests as follows:

//kill the request
xhr.abort()

In AngularJS, the basic idea is similar, but with the help of promises, we can implement as:

var canceller = $q.defer();
$http.get("/users.php", {
        timeout: canceller.promise
    })
    .then(function(response) {
        $scope.movie = response.data;
    });
$scope.cancel = function() {
    canceller.resolve("user cancelled");
};

Cheers

Leave a Reply

Your email address will not be published. Required fields are marked *