AngularJS - 创建一个服务对象

AngularJS  - 创建一个服务对象

问题描述:

相反角中的邮件列表中发布的,我觉得这可能是更多的JavaScript问题。希望社会各界SO也可以给更快的响应。

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'];

它抛出一个异常

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

$ scope.resource = Player.Player.resource.get({_ ID:$ routeParams._id}); 也会引发错误

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

下面的作品。

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!

您正在创建一个工厂,这是做的非典型方式。你不希望返回一个实例。角会给你在你的控制器的一个实例。

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', { });
 })

下面是我写的一个CakePHP的REST服务交互的服务。我写了一段时间回来,只是把它作为一个例子,我可能会重构。

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

})。