Angularjs - Abort/cancel 运行 $http 调用

Angularjs - Abort/cancel running $http calls

我在 angularjs 中使用 Resource 接到了一个呼叫,但我遇到了一些问题,因为我无法中止它所做的每个呼叫。我用于自动完成的这种结构..是否可以从资源调用转换为 http?这是代码

var Resource = $resource(URL, {},{ getAutocompleteResults: { method: "GET", params: {text: ""} }});

var locked = false;
function getMoreData() {

    if(locked)
        return;
    locked = true;

    Resource.autoCompleteResults()
        .$promise.then(function(data) {
            $scope.autocompleteViewResults = data;
            locked = false;
        });

}

这是我迄今为止尝试过的方法,但没有成功。

$scope.autocompleteViewResults = function () {
            $http
                .get(URL, {
                    params: {
                        text = ""
                    }
                })
                .success(function (data) {
                    $scope.autocompleteViewResults = data;
                });
        };

或者如果有人知道替代方法..

$scope.autocompleteViewResults 变量被赋值 2 次。

试试这个:

$scope.autocompleteViewResults = {};
$scope.getResults = function(valueAsTyped) {
        $http
            .get(URL, {
                params: {
                    text: valueAsTyped
                }
            })
            .success(function (data) {
                $scope.autocompleteViewResults = data;
            });
  };

更新

如果您需要取消旧请求。

var promiseCanceller = $q.defer();
$scope.autocompleteViewResults = {};

$scope.getResults = function(valueAsTyped) {

        promiseCanceller.resolve('request cancelled'); // cancel currently running request
        $http
            .get(URL, {
                params: {
                    text: valueAsTyped
                },
                timeout: promiseCanceller.promise // pass promiseCanceller as the timeout
            })
            .success(function (data) {
                $scope.autocompleteViewResults = data;
            });
  };