29

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 Answer 1

25

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

Sign up to request clarification or add additional context in comments.

3 Comments

Does setting var Search = $resource(...) beforehand not do the trick? I suppose I'm still working out the idea of services and factories in angular. Also, my first try was with $http and it worked fine. I wanted to try out $resource as well, just to get a feel for using either. Thanks!
Hm var Search = $resource(...) is actually correct. However resource expects an object to be returned but you return an array? try setting isArray:true on your query method, similar issue groups.google.com/forum/#!topic/angular/MT1vIakNEVM
Why do you override the query parameter?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.