角度异步http自动完成

Angular async http autocomplete

本文关键字:http 异步      更新时间:2023-09-26

我想用Angular创建一个自动补全,因为这是我第一次接触Angular,所以我很困惑。

这是我的代码:

 MenuService.getAutocompleteData(term).then(function (response) {
            $scope.menuData = response.data;
        });

这就是我如何调用正在进行以下http调用的服务:

return $http({
            url    : autocompletePath,
            method : "POST",
            data   : {
                term: term
            }
        }).success(function (response) {
            return response;
        });

问题是,这似乎是同步的,当我键入快速字母时,我的浏览器会冻结。我看到它是关于".然后"承诺,但我不知道如何解决它。任何帮助都将不胜感激。

您执行HTTP请求,这是正确的,但您尝试在成功时返回结果。相反,你应该尝试在你的成功处理程序中做需要做的事情。

所以在你的服务中,你会做这样的事情:

    return $http({
        url    : autocompletePath,
        method : "POST",
        data   : {
            term: term
        }
    }); //note that there is no success handler in your service, because what's supposed to happen when the request completes, is the controller's business, not the service's. The service should only know where to get the data

你可以把你的控制器改成这样:

  MenuService.getAutocompleteData(term).success(function (response) {
        $scope.menuData = response.data;
    }); //note the success-handler

为什么不试试呢?https://angular-ui.github.io/bootstrap/#/typeahead