在哪里放置资源特定的逻辑

net*_*ilk 10 javascript rest angularjs

您能否帮助我考虑在AngularJS中放置资源(服务)特定业务逻辑的位置.我觉得在我的资源上创建一些类似模型的抽象应该很棒,但我不确定如何.

API调用:

> GET /customers/1
< {"first_name": "John", "last_name": "Doe", "created_at": '1342915200'}
Run Code Online (Sandbox Code Playgroud)

资源(在CoffeScript中):

services = angular.module('billing.services', ['ngResource'])
services.factory('CustomerService', ['$resource', ($resource) ->
  $resource('http://virtualmaster.apiary.io/customers/:id', {}, {
    all: {method: 'GET', params: {}},
    find: {method: 'GET', params: {}, isArray: true}
  })
])
Run Code Online (Sandbox Code Playgroud)

我想做点什么:

c = CustomerService.get(1)
c.full_name()
=> "John Doe"

c.months_since_creation()
=> '1 month'
Run Code Online (Sandbox Code Playgroud)

非常感谢任何想法.亚当

pko*_*rce 18

需要在域对象的实例上调用的逻辑的最佳位置是该域对象的原型.

你可以沿着这些方向写一些东西:

services.factory('CustomerService', ['$resource', function($resource) {

    var CustomerService = $resource('http://virtualmaster.apiary.io/customers/:id', {}, {
        all: {
            method: 'GET',
            params: {}
        }
        //more custom resources methods go here....
    });

    CustomerService.prototype.fullName = function(){
       return this.first_name + ' ' + this.last_name;
    };

    //more prototype methods go here....

    return CustomerService;    

}]);
Run Code Online (Sandbox Code Playgroud)

  • 另请参见angularjs.org主页,"连接后端"部分,mongolab.js选项卡/代码,其中prototype也用于扩展资源类. (2认同)