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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read