AngularJS-使用$resource.query和params对象

AngularJS-使用$resource.query和params对象,angularjs,query-parameters,angular-resource,Angularjs,Query Parameters,Angular Resource,我正在努力学习并找出一些文献记载较少的东西 考虑一下,我在服务器上有一个搜索方法,它接受查询参数并返回一组搜索结果,并响应GET/search.jsonroute(Rails-FWIW) 因此,对于jQuery,示例查询如下所示: $.getJSON('/search', { q: "javascript", limit: 10 }, function(resp) { // resp is an array of objects: [ { ... }, { ... }, ... ] });

我正在努力学习并找出一些文献记载较少的东西

考虑一下,我在服务器上有一个搜索方法,它接受查询参数并返回一组搜索结果,并响应
GET/search.json
route(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: [ { ... }, { ... }, ... ]
    });
  }
}]);
并且认为:

<body ng-app="searchApp">
  ...
  <div ng-controller="SearchController">
    ...
    <form ng-submit="search()">...</form>
    ...
   </div>
</body>
初始化
$resource
一次,然后在请求的搜索中传递不同的查询参数,这似乎更直观。我想知道我是否做错了(很可能),或者只是误解了使用query params对象作为第一个参数调用
$resource.query
的文档。谢谢

TypeError:对象#没有方法“push”和$apply 进行中

因为您尚未定义名为“搜索”的资源。首先,您需要定义这样一个资源。下面是一个示例实现

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;
}]); 
将此模块包括在应用程序中,并在这样的控制器中使用

$scope.search_results = MyResource.search({
   query: 'foobar'  
}, function(result){}); 
然而,我不确定这是否是你所需要的。资源服务与RESTful服务器端数据源(又称RESTAPI)交互

也许您只需要一个简单的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.
  });

预先设置
var Search=$resource(…)
是否不起作用?我想我还在构思在安格尔建立服务和工厂的想法。另外,我的第一次尝试是使用
$http
,效果很好。我也想尝试一下
$resource
,只是想体验一下使用这两种工具的感觉。谢谢Hm var Search=$resource(…)实际上是正确的。然而,资源要求返回一个对象,而您却返回一个数组?尝试在查询方法上设置isArray:true,类似问题:为什么要覆盖查询参数?
 $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.
  });