where to place resource specific logic

2019-03-25 19:42发布

Can you help me please to consider where to place resource (service) specific business logic in AngularJS. I feel it should be great to create some model-like abstraction over my resource, but I'm not sure how.

API call:

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

Resource (in 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}
  })
])

I'd like to do something like:

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

c.months_since_creation()
=> '1 month'

Thanks a lot for any ideas. Adam

2条回答
对你真心纯属浪费
2楼-- · 2019-03-25 20:09

You might want to take a look at my answer to this SO question on related topic.

With such a solution, domain specific logic goes into custom domain entity class (in particular, its prototype).

查看更多
【Aperson】
3楼-- · 2019-03-25 20: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;    

}]);
查看更多
登录 后发表回答