【问题标题】:Cancel Previous Ajax Request and Start New One in Angularjs取消以前的 Ajax 请求并在 Angularjs 中开始新的请求
【发布时间】:2018-03-30 20:19:18
【问题描述】:

以下解决方案对我不起作用

How to cancel an $http request 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 调用

【问题讨论】:

    标签: angularjs angularjs-http


    【解决方案1】:

    您的代码的问题是 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");
      });;
    };
    

    【讨论】:

    • app.controller('SalesUserController', function ($scope, $compile, $http, $timeout, $filter) { _applyFunctions($scope, $compile, $http, $timeout, $filter ); });这是我的控制器。
    【解决方案2】:

    由于您在函数内部有取消对象并且还在调用它,所以 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 调用。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-26
      • 1970-01-01
      • 2019-09-03
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 2020-10-26
      • 2011-05-09
      相关资源
      最近更新 更多