[英]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. 我目前正在实现一个Angular提前输入,每次用户更改输入时都会从API提取数据。 The typeahead functions correctly if I add
typeahead-wait-ms=200
. 如果我添加
typeahead-wait-ms=200
则typeahead可以正常运行。 If I do not, I get an error of length of undefined.
如果不这样做,则会收到
length of undefined.
的错误length of undefined.
Here is the code: 这是代码:
HTML 的HTML
<input type="text" ng-model="selectedUser" typeahead="user for user in userTypeAhead($viewValue)">
JavaScript 的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. 代码通过后,
$scope.userTypeAheadResults
返回一个将在预输入中显示的userNames数组。 The array returns correctly, but before the function has returned, the error has already showed up in the console saying length of undefined
. 数组正确返回,但是在函数返回之前,错误已经在控制台中显示出来,提示
length of undefined
。 I have looked at several other questions here on stackoverflow and haven't had any luck. 我在这里查看了关于stackoverflow的其他几个问题,但没有任何运气。 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)
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.