Search code examples
angularjsangular-resource

How fetch the array from return of query method of a resource in AngularJS?


I have read the angularjs tutorial and now I am tryin to use in symfony application. I've implemented a rest client resource. The response json object has a sportEvents property which is an array. It is fetched.

var sportServices = angular.module('sportServices', ['ngResource']);

sportServices.factory('sportClient', ['$resource',
  function($resource){
    return $resource('rest/sport/events.json', {}, {
      query: {
          method:'GET', 
          transformResponse: function (data) {return angular.fromJson(data).sportEvents},
          isArray: true // The sportEvents property is an array.
      }
    });
  }]);

And my controller:

var sportControllers = angular.module('sportControllers', []);

sportControllers.controller('SportEventListCtrl', ['$scope', 'sportClient',
    function($scope, sportClient) {
      $scope.sportEvents = sportClient.query();
}]);

sportClient.query(); this is not an array, I cannot iterate it. And that's my question how can I achieve that the sportClient.query() returns with an array? because I have to group the elements and for this I need to iterate over the elements.

So a sample response:

{"sportEvents": [{id: 2234, number: 43545, name:"random"}, {id: 2235, number: 43546, name:"random"}]}

But this is the funny part: console.log( BetClient.query() ); in the controller the command gives the following result in the console:

[$promise: Object, $resolved: false]

And yes, in this object I see the entries, but I would like to transform it to an array somehow :)


Solution

  • There isn't anything "major" wrong with your code but in case you receive $promise, then resolve it first instead of assigning it directly to $scope.sportEvents.

    With asynchronous calls, like $http, you'll receive a promise that yes, something will be returned. When operation finishes, you can either resolve the promise for data or in case of error, reject it.

    So this service

    app.factory('JsonResource', function($resource) {
      return $resource('events.json', {}, {
        query: {
          method: 'GET',
          transformResponse: function(data) {
            return angular.fromJson(data).events;
          },
          isArray: true
        }
      });
    });
    

    And usage

    app.controller('MyCtrl', function($scope, JsonResource) {
      // No direct assignment here, resolve first, then assign
      JsonResource.query().$promise.then(function(data) {
        $scope.events = data;
      });
    });
    

    Should work just fine with your JSON format.

    {
      "id": 1,
      "events": [{
        "id": 2234, 
        "number": 43545, 
        "name": "random"
      },{
        "id": 2235, 
        "number": 43546, 
        "name": "random"
      }]
    }
    

    See related Plunker here http://plnkr.co/edit/Geklnp