12

I am trying to use $resource to get data from a static json file and here is the code snippet :

 angular.module('app.services', ['ngResource']).
  factory('profilelist',function($resource){
    return $resource('services/profiles/profilelist.json',{},{
        query:{method:'GET'}
    });
});

In the controller,

function ProfileCtrl($scope,profilelist) {
$scope.items = [];
$scope.profileslist = profilelist.query();
for (var i=0;i<=$scope.profileslist.length;i++){
    if($scope.profileslist[i] && $scope.profileslist[i].profileid){
        var temp_profile = $scope.profileslist[i].profileid;
    }
    $scope.items.push(temp_profile);

}

But now, I am facing an error : TypeError: Object #<Resource> has no method 'push'

Could you please help me where I am going wrong ?

codejammer
  • 469
  • 1
  • 7
  • 18

1 Answers1

21

You don't need to specify actions parameter for default $resource methods (these are 'get', 'save', 'query', 'remove', 'delete'). In this case you can use .query() method as is (this requires only service definition to be chaged):

angular.module('app.services', ['ngResource']).
  factory('profilelist',function($resource){
    return $resource('services/profiles/profilelist.json');
  });

P.S. And one more hint is that your example unwrapped json into hash rather then array (that's why you received no push method error), if you need it to be an array set isArray: true to action config:

'query':  {method:'GET', isArray:true}

And as @finishingmove spotted you really can't assign $resource result to obtain immediately, provide callback:

$scope.profileslist = profilelist.query(function (response) {
    angular.forEach(response, function (item) {
        if (item.profileid) {
            $scope.items.push(item.profileid);
        }
    });
});
developer033
  • 24,267
  • 8
  • 82
  • 108
Dmitry Evseev
  • 11,533
  • 3
  • 34
  • 48
  • Thanks a lot Dmitry Evseev. I tried the following code as well and it worked,but your answer is easier ! `angular.module('upe.services', ['ngResource']). factory('Profileslst', function($resource){ return $resource('services/profiles/:profileid.json', {}, { query: {method:'GET', params:{profileid:'profilelist'}, isArray:true} }); });` – codejammer Mar 17 '13 at 22:22