取消上一个 Ajax 请求并在 Angularjs 开始新请求

Cancel Previous Ajax Request and Start New One in Angularjs

以下解决方案在某种程度上对我不起作用

上述解决方案效果 - 中止新的 ajax 调用也应该允许新的 ajax 调用并中止旧的 ajax 调用

我的代码

$scope.callajax = function () {

        var canceller = $q.defer();


                    var data = {};
                        data['id'] = id;

                    $http({
                        method: "post",
                        url: url,
                        data: $.param(data),
                        timeout: canceller.promise,
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                    }).success(function (response) {

                    });


            canceller.resolve();


    };

我正在调用这个函数,如果我一次调用这个函数两次那么它应该先中止 ajax 调用并触发新的 ajax 调用

因为你在函数中有取消对象并调用它,callajax 函数每次都会调用然后取消它。为了实现你想要的,你应该尝试这样的事情 -

$scope.cancelHandles = [];
$scope.currentIndex=0;
$scope.callajax = function () {
   var cancelar = $q.defer();
   $scope.cancelHandles.push(cancelar);
   //rest of your code goes here except the last line cancelar.resolve();
   $scope.currentIndex = cancelHandles.length;
}
$scope.cancelAjaxCall = function(index) {
   cancelHandles[index].resolve();
}

函数调用 - callajax 应返回取消处理程序数组中的索引,该索引将映射到您调用 ajax 函数的次数。 有一个名为 cancelAjaxCall 的单独函数,它将接受一个索引,即您要取消的第 n 个 ajax 调用。

如果您想取消从现在开始的第 3 次调用,只需从 $scope.currentIndex 中减去 3 并调用 cancelAjaxCall 函数,即 cancelAjaxCall($scope.currentIndex-3);

您的代码的问题是 canceller.resolve() 被调用并立即取消 $http。以下通过标记 ajax 呼叫是否处于活动状态并取消呼叫来工作。

JSFiddle

var canceller,
    isSending = false;

$scope.callajax = function () {
    console.log("callajax");
    if(isSending) {
        canceller.resolve()
    }
    isSending = true;
    canceller = $q.defer();

    var data = {
            html: "<p>Text echoed back to request</p>",
            delay: 5
        }
    $http({
        method: "post",
        url: "/echo/html",
        data: data,
        timeout: canceller.promise
    }).success(function (response) {
        isSending = false;
        console.log("success");
    }).error(function(data, status) {            
        isSending = false;
        console.log("error");
  });;
};