更好的办法来设计AngularJS服务 [英] The better approach to design AngularJS services
问题描述
我在写这将与REST服务器交互的AngularJS客户端应用程序。
I'm writing an AngularJS client application that would interact with a REST server.
要管理我使用的是 $资源抽象的客户机/服务器的交互。
其实我写的每资源作为一个分离服务并只有在它注入控制器是要去使用它。
To manage the client / server interaction I'm using the $resource abstraction. Actually I'm writing every resource as a separated service and injecting it only in the controllers that are gonna use it.
我已经开始使用 angularjs种子的发展,所以在我separed services.js
文件我已经得到的服务越来越多:
I've started to develop using the angularjs-seed, so in my separed services.js
file I've got an increasing number of services:
angular.module('testReqService', ['ngResource']).
factory('TestReq', function($resource){
return $resource('http://test-url.com/api/test', {}, {});
});
angular.module('registerService', ['ngResource']).
factory('Register', function($resource){
return $resource('http://test-url.com/api/user/new', {}, {});
});
//More services here...
一切工作正常,但我不知道这是否是最好的办法。
Everything works fine, but I'm wondering if this is the best approach.
那么,是更好地为不同的 REST
请求编写单独的服务,并只在需要的时候,还是一个更好的方法是写一个单一的服务控制器注入它们不同的方法和网址为每个请求?
So, is better to write separate services for different REST
requests and inject them only in the controllers that need it, or a better approach is to write a single service with different methods and URL for every request?
推荐答案
我preFER第二种方式:
I prefer the second approach:
var resources = angular.module("myapp.resources", ['ngResource']);
resources.factory('Constants', [
function() {
return {
RESOURCE_URL: "http://www.example.com/rest"
}
}
]);
resources.factory('Rest', ['Constants', '$resource', function(C, $resource) {
return {
Users: $resource(C.RESOURCE_URL + '/users/:id', {
id: '@id',
}, {})
, Posts: $resource(C.RESOURCE_URL + '/posts/:user', {
user: '@'
}, {})
}
}]);
当你有几个资源,变得非常讨厌来管理你的所有控制器的依赖关系。这样一来,你所要做的就是注入一个。同时,这也是在我看来,更容易阅读器时,就明白了:
When you have several resources, become very annoying to manage all the dependencies in your controller. That way, all you have to do is inject a single one. It is also, in my opinion, easier to understand when reading the controller:
$scope.user = Rest.Users.get({id: 1});
更可以理解的。
$scope.user = Users.get({id: 1});
这篇关于更好的办法来设计AngularJS服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!