gpt4 book ai didi

javascript - 无法使用资源将值加载到 Angular-bootstrap typeahead 值中

转载 作者:太空宇宙 更新时间:2023-11-04 15:53:43 25 4
gpt4 key购买 nike

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

工作代码

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

哈巴狗模板代码

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.getContact.search 之间的区别在于,第一个返回 promise ,而后者则不返回。任何 $resource 方法通常都会解析为实际响应。我将通过一个例子来展示这一点。

使用$http获取数据

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

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

使用$resource获取数据

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

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

<小时/>

解决方案

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

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

请告诉我它是否适合您。

关于javascript - 无法使用资源将值加载到 Angular-bootstrap typeahead 值中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42889648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com