在哪里放置资源特定逻辑

2024-05-11

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

API调用:

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

资源(CoffeeScript 中):

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'

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


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

你可以按照这些思路写一些东西:

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;    

}]);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在哪里放置资源特定逻辑 的相关文章