Angularjs - 中止/取消运行$ http调用

时间:2015-02-23 08:28:41

标签: javascript angularjs autocomplete angular-resource angular-http

我在angularjs中使用资源进行了调用,但是我遇到了一些问题,因为我无法中止每次调用。我用于自动完成的这种结构..是否可以从资源调用转换为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;
                });
        };

或者,如果有人知道另一种方法..

1 个答案:

答案 0 :(得分:2)

$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;
            });
  };