使用AngularJS的$资源查询数据库 [英] Using AngularJS's $resource to query a database
问题描述
我已经创建了一个通过一个URL,建立在的node.js
,前press.js工作的API
,的MongoDB
和 angular.js
。
I've created an API that works via a url, built on node.js
, express.js
, mongoDB
and angular.js
.
我的API调用是这样的:
My API is called like this:
app.get('/ API /职位/:查询',api.postsQuery);
所以,如果我键入本地主机:3000 / API /职位/< whateverquery>
,MongoDB的吐出所有相关JSON到我的浏览器,所以这工作得很好
So if I type localhost:3000/api/posts/<whateverquery>
, mongoDB spits out all the pertinent JSON to my browser, so this is working just fine.
不过,我想起来这个链接到我的角前端,而且它造成的问题。我希望用户能够搜索到的格式,并有我的数据库返回正确的记录。这里是我的控制器:
However, I'm trying to link this up to my Angular front-end, and it's causing issues. I want the user to be able to search into a form and have my database return the correct records. Here's my controller:
function indexCtrl($scope, $http, $resource) {
$scope.itemSearch = $resource('http://localhost\\:3000/api/posts/:query',
{query:''}, {get:{method:'JSONP'}});
$scope.doSearch = function(){
$scope.posts = $scope.itemSearch.get({query:$scope.searchTerm});
console.log($scope.posts[1]) // returns undefined
}
}
我的问题是,当我运行 $ scope.doSearch
,我看到这样的Chrome的面板资源的查询:这样确实正在加载正确的数据,但它本身不是连接到 $ scope.posts
。
My issue is that when I run $scope.doSearch
, I see the query in Chrome's resources panel like this: so the correct data is indeed being loaded, but it's not attaching itself to $scope.posts
.
我有一种感觉,这可能是因为我需要一个回调函数;我试着用回调:JSON_CALLBACK
但打乱了我的查询/ API(因为它增加了一个回调= ...
到 $资源
呼叫的结束,这打破了查询)。
I have the feeling this might be because I need a callback function; I tried using callback: JSON_CALLBACK
but that messes up my query/API (because it adds a ?callback=...
to the end of the $resource
call and this breaks the query).
这是什么,我可以在这里做任何想法得到它的工作?该问题是缺乏一个回调?也许我可以添加一些正则表达式的 app.get
通话,后:查询
允许任何通配符之后>
Any ideas on what I can do here to get it working? Is the problem a lack of a callback? Perhaps I can add some regex to the app.get
call, after :query
to allow any wildcards afterward>
推荐答案
回调添加到您的$资源来电:
Add the callback to your $resource call:
$scope.doSearch = function(){
$scope.itemSearch.get({query:$scope.searchTerm}, function(data){
$scope.posts = data.posts;
console.log($scope.posts[1]);
});
};
在文档声明,他们利用回调:
var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123}, function(u, getResponseHeaders){
u.abc = true;
u.$save(function(u, putResponseHeaders) {
//u => saved user object
//putResponseHeaders => $http header getter
});
});
这篇关于使用AngularJS的$资源查询数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!