【问题标题】:Angular Typeahead returns before API call has returned - causing 'Length of Undefined' errorAngular Typeahead 在 API 调用返回之前返回 - 导致“未定义长度”错误
【发布时间】:2016-05-25 22:54:34
【问题描述】:

我目前正在实现一个 Angular typeahead,每次用户更改输入时,它都会从 API 中提取数据。如果我添加typeahead-wait-ms=200,则预输入功能正常。如果我不这样做,我会收到 length of undefined. 的错误代码:

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)
    }); 
}  

当代码通过时,$scope.userTypeAheadResults 返回一个用户名数组,该数组将显示在预输入中。数组正确返回,但在函数返回之前,错误已经出现在控制台中,显示为length of undefined。我在stackoverflow上查看了其他几个问题,但没有任何运气。有任何想法吗? 提前致谢。

【问题讨论】:

  • 为什么你的条件是 $scope.data.array.length?而不是 data.array.length?
  • 对不起,是data.array.length。我的错。

标签: javascript angularjs promise typeahead


【解决方案1】:

返回承诺。

$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)
    }); 
}

【讨论】:

    猜你喜欢
    • 2017-05-09
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 2019-04-28
    • 2013-05-25
    • 2021-06-19
    • 2020-11-08
    相关资源
    最近更新 更多