How to cancel an $http request in AngularJS ?
Last Updated :
30 Jul, 2024
In AngularJS, we use different sources to fetch the data as per our needs. We call different data source APIs using $http requests. We can fetch the data along with cancelling the real-time running request. In AngularJS, we can use the $q service along with the promises to cancel the request. Also, there is a timeout() utility, which can cancel an $http request in AngularJS. In this article, we will see how we can demonstrate the live fetching of data and also simultaneously cancel the running http request.
Steps to Cancel an $http request in AngularJS
The below steps will be followed to cancel an $http request in AngularJS Applications.
Step 1: Create a new folder for the project. We are using the VSCode IDE to execute the command in the integrated terminal of VSCode.
mkdir cancel-http
cd cancel-http
Step 2: Create the index.html file in the newly created folder, we will have all our logic and styling code in this file.
We will understand the above concept with the help of suitable approaches & will understand its implementation through the illustration.
Cancelling an $http request using deferred object ($q.defer())
In this approach, we are cancelling the HTTP requests made to the "https://jsonplaceholder.typicode.com/comments/" using a deferred object created with the '$q.defer()'. Here when we click on the "Fetch Data" button, the HTTP request is initiated using the "$http.get" method and this retrieves the ssampe comments from the API endpoint. There is a 'canceler' object that is created using the '$q.defer()' method that has the promise that can be used to cancel the request when the Cancel button is been clicked. The data which is fetched is displayed with a delay of 2 seconds.
Example: Below is an example that demonstrates the cancellation of an $http request in AngularJS using a deferred object ($q.defer()).
HTML
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
</script>
<style>
h1 {
color: green;
}
</style>
</head>
<body ng-controller="MainCtrl">
<h1>GeeksforGeeks</h1>
<h3>
Approach 1: Using deferred object ($q.defer())
</h3>
<div>
<button ng-click="fetchData()"
ng-disabled="fetching">
Fetch Data
</button>
<button ng-click="cancelRequest()">
Cancel
</button>
</div>
<div>
<p ng-repeat="title in fetchedData">
{{title}}
</p>
</div>
<div>
<h2>Request Log:</h2>
<p ng-repeat="request in requestLog track by $index">
{{request.method}}
Request {{request.id}} URL: {{request.url}}
</p>
</div>
<script>
angular.module('myApp', [])
.controller('MainCtrl', function ($scope, $http, $q, $timeout) {
var canceler;
$scope.fetchedData = [];
$scope.requestLog = [];
$scope.fetching = false;
var requestId = 1;
$scope.fetchData = function () {
$scope.fetching = true;
canceler = $q.defer();
fetchComment(1);
}
$scope.cancelRequest = function () {
if (canceler) {
canceler.resolve('Request canceled');
$scope.fetching = false;
alert('Request Canceled');
}
};
function fetchComment(commentId) {
$http.get('.../example.com/' +
commentId, { timeout: canceler.promise })
.then(function (response) {
if (response.data && response.data.name) {
var title = response.data.name;
$scope.fetchedData.push(title);
}
$scope.requestLog.push({
id: commentId,
method: 'GET',
url: '../example.com/'
+ commentId,
headers: JSON.stringify(response.headers())
});
if ($scope.fetching) {
$timeout(function () {
fetchComment(commentId + 1);
}, 2000);
}
})
.catch(function (error) {
if (error && error.status === -1) {
} else {
$scope.fetching = false;
}
});
}
});
</script>
</body>
</html>
Output:
Cancelling an $http request using $timeout.cancel()
In this approach, we are using the $timeout.cancel() service to cancel the HTTP requests. When we click on the "Fetch Posts" button, the fetchPost function is been triggered which uses the $timeout service to make the delayed HTTP request. Also, the $timemout service returns the promise which represents the timer for the delayed function. When we click on the "Cancel" button, the "cancelRequest" function is been triggered in which we are using the "$timeout.cancel(requestPromise)" to cancel the delayed unction and the HTTP request.
Example: Below is an example that demonstrates the cancellation of an $http request in AngularJS using $timeout.cancel() in AngularJS.
HTML
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
</script>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-resource.min.js">
</script>
<style>
h1 {
color: green;
}
</style>
</head>
<body ng-controller="MainCtrl">
<h1>GeeksforGeeks</h1>
<h3>
Approach 2: Using $timeout.cancel() in AngularJS
</h3>
<div>
<button ng-click="fetchData()"
ng-disabled="fetching">
Fetch Posts
</button>
<button ng-click="cancelRequest()">
Cancel
</button>
</div>
<div>
<p ng-repeat="post in fetchedData">
{{post.title}}
</p>
</div>
<div>
<h2>Request Log:</h2>
<p ng-repeat="request in requestLog track by $index">
{{request.method}}
Request {{request.id}} URL: {{request.url}}
</p>
</div>
<script>
angular.module('myApp', ['ngResource'])
.controller('MainCtrl',
function ($scope, $resource, $timeout, $http) {
var requestPromise;
$scope.fetchedData = [];
$scope.requestLog = [];
$scope.fetching = false;
var requestId = 1;
$scope.fetchData = function () {
$scope.fetching = true;
fetchPost(1);
}
$scope.cancelRequest = function () {
if (requestPromise) {
$timeout.cancel(requestPromise);
$scope.fetching = false;
alert('Request Canceled');
}
};
function fetchPost(postId) {
requestPromise = $timeout(function () {
$http.get('.../example.com/'
+ postId)
.then(function (response) {
if (response.data && response.data.title) {
var post = response.data;
$scope.fetchedData.push(post);
}
$scope.requestLog.push({
id: postId,
method: 'GET',
url: '.../example.com/'
+ postId,
headers: JSON.stringify(response.headers())
});
if ($scope.fetching) {
fetchPost(postId + 1);
}
})
.catch(function (error) {
if (error && error.status === -1) {
} else {
$scope.fetching = false;
}
});
}, 2000);
}
});
</script>
</body>
</html>
Output:
Similar Reads
How to make an http call in angular
Angular, with its robust framework and extensive ecosystem, offers you powerful tools for building modern web applications. One such tool is the HttpClient module, which provides a seamless way to make HTTP calls and interact with RESTful APIs or backend services. In this article, we'll explore maki
3 min read
How to detect a route change in AngularJS ?
In this article, we will see how to detect a route change in AngularJS. In order to detect route change at any moment in AngularJS, this can be achieved by using the $on() method. The $on() method is an event handler, the event which will handle $routeChangeSuccess which gets triggered when route/vi
2 min read
How to call an AngularJS Function inside HTML ?
A Function is a set of statements that takes input, does some specific computation, and produces output. In this article, we will learn How to Call an AngularJS function inside HTML. To achieve this, we can use {{...}} to call the function from HTML. We can also pass arguments and return the result
3 min read
How to set, get and clear cookies in AngularJS ?
In this article, we will see how to set, get & clear the Cookies in AngularJS, along with understanding the basic usage through the implementation. In AngularJS, we need to use angular-cookies.js to set, get and clear the cookies. You can use the live CDN link for this: https://cdnjs.cloudflare.
2 min read
How AngularJS prefixes $ and $$ are used?
$: The $ in AngularJs is a built-in object.It contains application data and methods. The scope($) acts as a link between controller and view. Inside the controller function the properties and the methods to the scope($) can be attached. Expression, ng-model, or ng-bind directive can be used to displ
3 min read
How to determine active route in AngularJS ?
In this article, we will see how to determine the active route in AngularJS, along with understanding the basic implementation through the example. Approach: To determine which is the active route at any moment in AngularJS this can be achieved by using $on() & $location.path() method. An event
2 min read
How to cancel the current request in Ajax ?
In this article, we will see how to cancel the current request in Ajax. AJAX (Asynchronous JavaScript and XML) is a technique for creating fast and dynamic web pages. It allows a web page to update its content without reloading the entire page. An AJAX request is an HTTP request made using JavaScrip
4 min read
Make HTTP requests in Angular?
In Angular, making HTTP requests involves communicating with a server to fetch or send data over the internet. It's like asking for information from a website or sending information to it. Angular provides a built-in module called HttpClientModule, which simplifies the process of making HTTP request
4 min read
How to cancel XMLHttpRequest in AJAX ?
In this article, we will learn how can we stop or cancel the already sent HTTP request to the server. XMLHttpRequest is an object that we use to send an HTTP request to the server to get the required data from the server. XMLHttpRequest provides an abort() method to cancel the sent request to the se
2 min read
How to push elements in an array using AngularJS ?
Given an array and the task is to perform the push operation on the array using AngularJS. The arr.push() method is used to push one or more values into the array, & new values will add at the end of an array. This method changes the length of the array by the number of elements added to the arr
2 min read