【问题标题】:where to place resource specific logic在哪里放置资源特定的逻辑
【发布时间】:2012-08-18 01:33:04
【问题描述】:

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

API 调用:

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

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

【问题讨论】:

    标签: javascript rest angularjs


    【解决方案1】:

    您可能想看看我对相关主题的this SO question 的回答。

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

    【讨论】:

      【解决方案2】:

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

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

      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;    
      
      }]);
      

      【讨论】:

      • 另见 angularjs.org 主页,“连接后端”部分,mongolab.js 选项卡/代码,其中原型也用于扩展资源类。
      猜你喜欢
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      • 1970-01-01
      • 2011-12-16
      • 2011-06-03
      • 2011-08-02
      • 1970-01-01
      • 2014-03-16
      相关资源
      最近更新 更多