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 ?

2
  • 1
    I am not sure, but notice that .query() is not a synchronous operation, meaning you cannot iterate over the results immediately. Commented Mar 17, 2013 at 22:09
  • You are right. I used a callback to iterate over the results. Commented Mar 18, 2013 at 13:53

1 Answer 1

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);
        }
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

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

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.