数据服务应属于哪个模块? AngularJS

时间:2015-03-20 11:35:18

标签: angularjs

假设我的应用程序中有3个模块。主要模块和两个功能模块(客户和发票)。我定义了一个'CustomerService'来从REST api中检索数据。此服务在“app.customer”模块中定义,并在同一模块的“CustomerListController”中用于显示客户列表。

现在,我在发票模块的'InvoiceEditController'中使用相同的'CustomerService'来在创建发票时为用户填充下拉列表。

angular.module('app', ['app.customer','app.invoice']);

angular.module('app.customer', ['ngResource'])
.factory('CustomerService', ['$resource',
     function($resource) {
         return $resource('http://rest.com/customers/:id');
     }
])
.controller('CustomerListController', ['$scope', 'CustomerService',
     function($scope, CustomerService) {
         $scope.customers = CustomerService.get();
     }
]);

angular.module('app.invoice', []);
.controller('InvoiceEditController', ['$scope', 'CustomerService',
     function($scope, CustomerService) {
         $scope.customers = CustomerService.get();
     }
]);

CustomerService应该在app.customer模块中分组,还是应该一起创建一个新模块和组数据服务提供者(例如:CustomerService,ProductService,InvoiceService到app.services模块中)?

后者的原因可能是因为您想要隔离依赖项。也就是说,控制器可能不需要'ngResource'模块作为服务的依赖。

但是,将服务组合在一起将导致模块具有来自不同功能的服务(可能彼此无关)。

目前的指导方针是什么?

1 个答案:

答案 0 :(得分:0)

我相信这与您要解决的问题非常相关。在我看来,服务是应用程序的共同点,因为正如您所提到的,它们可以在您的应用程序的多个功能中重用,而且将来可能会被其他功能使用。所以我建议创建一个名为“Common”的新模块并将服务放在那里。

希望它有所帮助。 干杯!

相关问题