我正在尝试接听 angular.js
并致力于找出一些记录较少的事情。
考虑一下 - 我在服务器上有一个搜索方法,它接受查询参数并返回搜索结果集合,并响应 GET /search.json
路线(Rails FWIW)。
所以jQuery
,示例查询如下所示:
$.getJSON('/search', { q: "javascript", limit: 10 }, function(resp) {
// resp is an array of objects: [ { ... }, { ... }, ... ]
});
我正在尝试使用 Angular 来实现它,并了解它是如何工作的。这就是我现在拥有的:
var app = angular.module('searchApp', ['ngResource']);
app.controller('SearchController', ['$scope', '$resource', function($scope, $resource){
$scope.search = function() {
var Search = $resource('/search.json');
Search.query({ q: "javascript", limit: 10 }, function(resp){
// I expected resp be the same as before, i.e
// an array of Resource objects: [ { ... }, { ... }, ... ]
});
}
}]);
在 View 中:
<body ng-app="searchApp">
...
<div ng-controller="SearchController">
...
<form ng-submit="search()">...</form>
...
</div>
</body>
但是,我不断收到类似 TypeError: Object #<Resource> has no method 'push'
的错误和$apply already in progress
。
如果我更改$resource
,事情似乎会按预期进行。初始化如下:
var Search = $resource("/search.json?" + $.param({ q: "javascript", limit: 10 }));
Search.query(function(resp){ ... });
初始化 $resource
似乎更直观一次,然后根据请求的搜索的变化传递不同的查询参数。我想知道我是否做错了(最有可能)或者只是误解了调用 $resource.query
的文档使用查询参数对象作为第一个参数是可行的。谢谢。
最佳答案
TypeError: Object # has no method 'push' and $apply already in progress
因为您尚未定义名为搜索的资源。首先您需要定义这样的资源。 Doc: $resource 。这是一个示例实现
angular.module('MyService', ['ngResource'])
.factory('MyResource', ['$resource', function($resource){
var MyResource = $resource('/api/:action/:query',{
query:'@query'
}, {
search: {
method: 'GET',
params: {
action: "search",
query: '@query'
}
}
});
return MyResource;
}]);
将此模块包含在您的应用程序中并在像这样的 Controller 中使用它
$scope.search_results = MyResource.search({
query: 'foobar'
}, function(result){});
但是我不确定这是否是您所需要的。资源服务与 RESTful 服务器端数据源(也称为 REST API)交互。
也许您只需要一个简单的 http get:
$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
关于AngularJS - 将 $resource.query 与 params 对象一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16708081/