简体   繁体   中英

Angular async http autocomplete

I want to create an autocomplete with Angular and since this is my first contact with angular, I`m pretty stucked.

Here is my code:

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

This is how I call a service that is making the following http call:

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

The problem is that it seems that is syncronously and my browser freezes when I type fast letters. I saw that it is about that ".then" promise, but I`m not sure how to fix it. Any help would be appreciated.

You do a HTTP-request, which is correct, but you try to return the result on success. Instead you should try to do what needs to be done in your success-handler.

So in your service you would do something like this:

    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

And you would change your controller to this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM