无法使用资源将值加载到 angular-bootstrap 预输入值中

Could not load value into angular-bootstrap typeahead values with resources

我的 angular-ui typeahead 组件有问题。它不显示由 angular 资源填充的值,但是使用 $http 效果很好。我想我在这里遗漏了一些使用异步调用和正确填充返回值的技巧。

工作代码

$scope.searchForContact = function(val) {
  return $http.get('/api/contacts/search', {
    params: {
    q: val
  }
}).then(function(response){
  return response.data.map(function(item){
    return item.name;
  });
});

};

代码无效

$scope.searchForContact = function(val) {
  return Contact.search({q: val}, function(response){
    return response.map(function(item){
      return item.name;
    });
  });
});

...

'use strict';

app.factory("Contact", function($resource, $http) {
var resource = $resource("/api/contacts/:id", { id: "@_id" },
{
  'create':  { method: 'POST' },
  'index':   { method: 'GET', isArray: true },
  'search':  { method: 'GET', isArray: true, url: '/api/contacts/search', params: true },
  'show':    { method: 'GET', isArray: false },
  'update':  { method: 'PUT' },
  'destroy': { method: 'DELETE' }
}
);

 return resource;
});

Pug 模板代码

input.form-control(
  type='text'
  ng-model='asyncSelected'
  uib-typeahead='contact for contact in searchForContact($viewValue)'
  typeahead-loading='loadingLocations'
  typeahead-no-results='noResults'
)
i.glyphicon.glyphicon-refresh(ng-show='loadingLocations')
div(ng-show='noResults')
  i.glyphicon.glyphicon-remove
  |
  |No Results Found

Angular 资源工作正常,包括搜索端点 - 我只是在搜索端点返回的页面结果上输出。在这两个结果中应该只是一个带有字符串值的数组。我做错了什么?

$http.get 和您的 Contact.search 之间的区别在于第一个 return 是承诺而后者不是。任何 $resource 方法通常都会解析为实际响应。我会用一个例子来说明。

使用 $http 获取数据

var httpResult = $http.get('http://some.url/someResource').then(function(response) {
    return response.map(function(item) { return item.name });
});

httpResult对象包含一个promise,所以我们需要使用then方法来获取实际数据。此外,承诺 解析为映射数组,这是预期的结果。

使用 $resource 获取数据

var someResource = $resource('http://some.url/someResource');
var resourceResult = someResource.query(function(response) {
    return response.map(function(item) { return item.name });
});

resourceResult不是这里的承诺。这是一个 $resource 对象,它将包含来自服务器的响应后的实际数据(简而言之,resourceResult 将是联系人数组 - 原始的,未映射的,即使有映射功能).但是,$resource 对象包含一个 $promise 属性,这是一个类似于由 $http.get 编辑的 return 的承诺。在这种情况下它可能会有用。


解决方案

我在文档中读到,为了使 uib-typehead 正常工作,$scope.searchForContact 需要 return 一个承诺。我不会将回调函数传递给 search,而是简单地将它与 $resource 对象的 $promise 链接起来使其工作。

$scope.searchForContact = function(val) {
  return Contact.search({q: val}).$promise.then(function(response){
    return response.map(function(item){
      return item.name;
    });
  });
});

让我知道它是否适合你。