var myApp = angular.module('CancellableApp', []);
myApp.controller('CancellableController', ['$scope', '$http', '$q',
function($scope, $http, $q) {
$scope.canceller = $q.defer();
$scope.status = "No Request";
//You can change the URL to whaterver works for you, this is just for demonstration and deployed on my local
$scope.url = "http://10.234.99.220:8081/demo/1.post";
$scope.cancelRequest = function() {
if ($http.pendingRequests.length <= 0) {
//If I use get method here, clicking the "Send Request" button will cancel the previous request and start
//a new request. While for post, it won't work
$http.get($scope.url, {
timeout: $scope.canceller.promise,
headers:{"Content-Type": "text/plain"}
}).success(function() {
$scope.status = "No Request"
}).error(function() {
$scope.status = "No Request"
});
} else {
console.log($http.pendingRequests[0]);
$scope.canceller.resolve();
//Re-initialize the canceller after it is resolved, otherwise it will cancel all the incoming request.
$scope.canceller = $q.defer();
$scope.status = "Request Cancelled and new request pending";
//Then start a new request
//If I use get method here, clicking the "Send Request" button will cancel the previous request and start
//a new request. While for post, it won't work
$http.get($scope.url, {
timeout: $scope.canceller.promise,
headers:{"Content-Type": "application/json"}
}).success(function() {
$scope.status = "No Request"
}).error(function() {
$scope.status = "No Request"
});
$scope.status = "Request Pending";
}
};
}
]);
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.6/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="CancellableApp">
<div ng-controller="CancellableController">
Click "Send Request" quickly to send new request and cancel previous pending requests. <br/>
<br/>
<input ng-model="url" value='{{url}}' type="text" style="width:50%"/>
<button ng-click="cancelRequest()">Send Request</button>
<p>{{status}}</p>
</div>
</body>
</html>
/* Put your css in here */