Angularjs bootstrap typeahead not working: Error: [filter:notarray]

Angularjs bootstrap typeahead not working: Error: [filter:notarray]

我需要使用 typeahead 进行 http 调用来获取建议选项

$scope.getlist = function getListofNames(name) {
 return $http({
   method: 'GET',
     url: '/v1/'+name,
     data: ""
 }).then(function(response){

     if(response.data.statusMessage !== 'SUCCESS'){
         response.errorMessage = "Error while processing request. Please retry."
           return response;
     }

         else {
           return response.data.payload;
         }

       }, function(response){
       response.errorMessage = "Error while processing request"
           return response;
       }
       );
}

response.data.payload 是一个对象数组,已成功获取但出现此错误 错误:[filter:notarray] http://errors.angularjs.org/1.4.5/filter/notarray?

注意:我使用的是 angular 1.4.5 和 Bootstrap v3.1.1

我猜你的预输入标记看起来像这样:

<input [...] typeahead="item in getItems($viewValue) | filter: $viewValue">

为什么它不起作用:

当项目数组异步获取 时会出现问题。在您的情况下,getItems 函数被称为 getListofNames,并且您的项目确实是异步获取的,因为调用了 $http。因此在错误发生时,getListofNames() 仍然是一个未解决的 promise 对象,还不是名称数组。

你怎么做到的:

从模板中删除过滤器。您应该在 getItems 中返回数组之前对其进行过滤。 理想情况下,您希望在服务器端进行过滤。实际上,服务器接收到用户键入的子字符串(这是 $viewValue 参数),因此它具有过滤数组的所有数据。这将阻止返回所有元素并使响应更短。 或者,您可以在承诺的回调中过滤客户端:

$scope.getList = function getListofNames(name) {
    return $http(...}).then(
        function(response){
            // filter response.data.payload according to 
            // the 'name' ($viewValue) substring entered by the user
            return filteredArray; // <- no need to pipe a filter in the template anymore
        }
    );
};