简体   繁体   中英

Angular Typeahead returns before API call has returned - causing 'Length of Undefined' error

I am currently implementing an Angular typeahead that is pulling data from an API each time the user changes the input. The typeahead functions correctly if I add typeahead-wait-ms=200 . If I do not, I get an error of length of undefined. Here is the code:

HTML

<input type="text" ng-model="selectedUser" typeahead="user for user in userTypeAhead($viewValue)">

JavaScript

$scope.userTypeAhead = function(userTypeAheadInput){
    myService.searchUserTypeAhead(userTypeAheadInput).then(function(data) {

        $scope.userTypeAheadResults = [];

        for (i = 0; i < data.array.length; i++) {
             $scope.userTypeAheadResults.push(data.array[i].userName);
        }

        return $scope.userTypeAheadResults;

    }, function(error) {
        console.log(error)
    }); 
}  

When the code goes through, $scope.userTypeAheadResults returns an array of userNames that will show in the typeahead. The array returns correctly, but before the function has returned, the error has already showed up in the console saying length of undefined . I have looked at several other questions here on stackoverflow and haven't had any luck. Any ideas? Thanks in advance.

Return the promise.

$scope.userTypeAhead = function(userTypeAheadInput){
    // return the promise
    return myService.searchUserTypeAhead(userTypeAheadInput).then(function(data) {

        $scope.userTypeAheadResults = [];

        for (i = 0; i < $scope.data.array.length; i++) {
             $scope.userTypeAheadResults.push(data.array[i].userName);
        }

        return $scope.userTypeAheadResults;

    }, function(error) {
        console.log(error)
    }); 
}

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