Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  156] [ 7]  / answers: 1 / hits: 17259  / 12 Years ago, thu, june 28, 2012, 12:00:00

Instead of posting in Angular mailing list, I think this may be more of javascript question. Hope the SO community can also give faster response.



I am trying to encapsulate the data in a service and injecting into controller.



angular.module('myApp.services', ['ngResource']).
factory('Player', function($resource){
var Player ;
Player = {
resource: $resource('/api/Player/:_id', {} )
};
return Player
});


function PlayerDetailCtrl(Player, $routeParams, $scope) {
$scope.resource = Player.resource.get({_id:$routeParams._id});
}
PlayerDetailCtrl.$inject = ['Player', '$routeParams', '$scope'];


It throws an exception



TypeError: Object #<Object> has no method 'query'


$scope.resource = Player.Player.resource.get({_id:$routeParams._id}); also throws error



TypeError: Object #<Object> has no method 'query'


the below works.



angular.module('myApp.services', ['ngResource']).
factory('Player', function($resource){
var Player ;
Player= $resource('/api/Player/:_id', {} )
return Player
});


function PlayerDetailCtrl(Player, $routeParams, $scope) {
$scope.resource = Player.Player.get({_id:$routeParams._id});
}
PlayerDetailCtrl.$inject = ['Player', '$routeParams', '$scope'];


my intention is to add more data and method to Player. So how can I make the first (object form) works!


More From » angularjs

 Answers
69

You are creating a factory, this is the atypical way of doing. You don't want to be returning an instance. Angular will give you an instance in your controller.



 factory('Player', function ($resource) { 
return $resource('/api/Player/:_id', { });
})


Here is a service I wrote to interact with a cakephp REST service. I wrote it a while back so just take it as an illustration, I may refactor.



 factory('CommentSvc', function ($resource) {
return $resource('/cakephp/demo_comments/:action/:id/:page/:limit:format', { id:'@id', 'page' : '@page', 'limit': '@limit' }, {
'initialize' : { method: 'GET', params: { action : 'initialize', format: '.json' }, isArray : true },
'save': { method: 'POST', params: { action: 'create', format: '.json' } },
'query' : { method: 'GET', params: { action : 'read', format: '.json' } , isArray : true },
'update': { method: 'PUT', params: { action: 'update', format: '.json' } },
});


}).


[#84586] Wednesday, June 27, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tye

Total Points: 415
Total Questions: 103
Total Answers: 116

Location: Iraq
Member since Fri, Jun 5, 2020
4 Years ago
;