0

in my html I have

typeahead="name for name in search($viewValue)

My data returned from server is as expected. But I have now realised that as this is a async request, the return I am doing in multiple places in the code below are worthless, as they are not returning the data array so that the html code above can receive it.

        $scope.search = function (term) {
            return $http({
                method: 'GET',
                url: 'rest/search',
                params: {
                    term: term,
                    types: '21'
                }
            }).
            success(function (data, status, headers, config) {
                var Names = [];
                for (var i = 0; i < data.length; i++) {
                    Names.push(data[i].name);
                }
                console.log(Names);//as expected

                return Names;
            }).
            error(function (data, status, headers, config) {
                console.log(status);
            });

        };

How should I return the data from a async HTTP GET request in an array form so that my typeahead can use it.

Should I store in a data variable like this example on HTTP GET success https://stackoverflow.com/a/12513509/494461

but then how can I run the function as well use the storage variable in the array?

typeahead="name for name in search($viewValue)

or

typeahead="name for name in dataStoredInHTTPGetSucess

can I somehow combine the above two?

1

1 Answer 1

1

This is more or less duplicate of https://stackoverflow.com/a/15930592/1418796. What you need to do is to return a promise from your function, something along those lines:

$scope.search = function (term) {
        return $http({
            method: 'GET',
            url: 'rest/search',
            params: {
                term: term,
                types: '21'
            }
        }).
        then(function (response) {
            var names = [];
            for (var i = 0; i < response.data.length; i++) {
                names.push(response.data[i].name);
            }
            console.log(names);//as expected

            return names;
        });

    };
Sign up to request clarification or add additional context in comments.

2 Comments

I have trouble understanding how your code is any different than the original code. Is the "then" function so much different to the "success" function?
@EasterBunnyBugSmasher apparently they are quite different. According to github.com/angular/angular.js/issues/10508 success and error return the original promise of get, while then returns a new promise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.