AngularJS - Using $resource.query with params object

风流意气都作罢 提交于 2019-12-03 03:38:28

问题


I'm trying to pick up angular.js and working on figuring out some of the things that are a bit less documented.

Consider this - I have a search method on the server that accepts query params and returns a collection of search results, and responds to GET /search.json route (Rails FWIW).

So with jQuery, a sample query would look like this:

$.getJSON('/search', { q: "javascript", limit: 10 }, function(resp) {
  // resp is an array of objects: [ { ... }, { ... }, ... ]
});

I'm trying implement this using angular, and wrap my head around how it works. This is what I have now:

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: [ { ... }, { ... }, ... ]
    });
  }
}]);

And in the view:

<body ng-app="searchApp">
  ...
  <div ng-controller="SearchController">
    ...
    <form ng-submit="search()">...</form>
    ...
   </div>
</body>

However, I keep getting errors like TypeError: Object #<Resource> has no method 'push' and $apply already in progress.

Things seem to work out as expected if I change the $resource initialization to the following:

var Search = $resource("/search.json?" + $.param({ q: "javascript", limit: 10 }));
Search.query(function(resp){ ... });

It seems more intuitive to initialize the $resource once and then pass different query parameters with changes in the requested search. I wonder if I'm doing it wrong (most likely) or just misunderstood the docs that calling $resource.query with the query params object as the first argument is feasible. thanks.


回答1:


TypeError: Object # has no method 'push' and $apply already in progress

because you have not defined a resources with the name Search. First you need to define such a resource. Doc: $resource. Here is an example implementation

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

Include this module in you app and use it in a controller like this

$scope.search_results = MyResource.search({
   query: 'foobar'  
}, function(result){}); 

However I am not sure if this is what you need. The resource service interacts with RESTful server-side data sources aka REST API.

Maybe you need just a simple 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.
  });

http://docs.angularjs.org/api/ng.$http



来源:https://stackoverflow.com/questions/16708081/angularjs-using-resource-query-with-params-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!