Javascript Angular Typeahead在API调用返回之前返回-导致';未定义的长度';错误
我目前正在实现一个Angular typeahead,每当用户更改输入时,它都会从API中提取数据。如果我添加Javascript Angular Typeahead在API调用返回之前返回-导致';未定义的长度';错误,javascript,angularjs,promise,typeahead,Javascript,Angularjs,Promise,Typeahead,我目前正在实现一个Angular typeahead,每当用户更改输入时,它都会从API中提取数据。如果我添加typeahead wait ms=200,则typeahead功能正常。如果我没有,我会得到一个length of undefined的错误。下面是代码: HTML JavaScript $scope.userTypeAhead = function(userTypeAheadInput){ myService.searchUserTypeAhead(userTypeAhe
typeahead wait ms=200
,则typeahead功能正常。如果我没有,我会得到一个length of undefined的错误。
下面是代码:
HTML
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)
});
}
$scope.userTypeAhead=函数(userTypeAheadInput){
searchUserTypeAhead(userTypeAheadInput)。然后(函数(数据){
$scope.userTypeAheadResults=[];
对于(i=0;i
当代码执行时,$scope.userTypeAheadResults
返回一个用户名数组,该数组将显示在typeahead中。数组返回正确,但在函数返回之前,控制台中已显示错误,提示length of undefined
。我已经在stackoverflow上查看了其他几个问题,但没有任何运气。有什么想法吗?
提前感谢。兑现承诺
$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)
});
}
$scope.userTypeAhead=函数(userTypeAheadInput){
//还债
返回myService.searchUserTypeAhead(userTypeAheadInput)。然后返回(函数(数据){
$scope.userTypeAheadResults=[];
对于(i=0;i<$scope.data.array.length;i++){
$scope.userTypeAheadResults.push(data.array[i].userName);
}
返回$scope.userTypeAheadResults;
},函数(错误){
console.log(错误)
});
}
退回承诺
$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)
});
}
$scope.userTypeAhead=函数(userTypeAheadInput){
//还债
返回myService.searchUserTypeAhead(userTypeAheadInput)。然后返回(函数(数据){
$scope.userTypeAheadResults=[];
对于(i=0;i<$scope.data.array.length;i++){
$scope.userTypeAheadResults.push(data.array[i].userName);
}
返回$scope.userTypeAheadResults;
},函数(错误){
console.log(错误)
});
}
为什么您的条件为$scope.data.array.length?不是data.array.length?对不起,是data.array.length。我的错误。为什么您的条件保持$scope.data.array.length?不是data.array.length?对不起,是data.array.length。我的错误。