10

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

接口调用:

> GET /customers/1
< {"first_name": "John", "last_name": "Doe", "created_at": '1342915200'}

资源(在 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}
  })
])

我想做类似的事情:

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

c.months_since_creation()
=> '1 month'

非常感谢您的任何想法。亚当

4

2 回答 2

18

The best place for logic that needs to be invoked on an instance of a domain object would be a prototype of this domain object.

You could write something along those lines:

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;    

}]);
于 2012-08-22T17:35:36.337 回答
0

您可能想看看我对相关主题的这个 SO 问题的回答。

使用这样的解决方案,特定领域的逻辑进入自定义领域实体类(特别是它的原型)。

于 2013-07-16T13:54:55.033 回答