AngularJS - Using $resource.query with params object

sa125 picture sa125 · May 23, 2013 · Viewed 83k times · Source

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.

Answer

Upvote picture Upvote · May 23, 2013

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