The better approach to design AngularJS services

陌路散爱 提交于 2019-12-03 10:48:05

问题


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.

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.

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?


回答1:


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

is more understandable that

$scope.user = Users.get({id: 1});


来源:https://stackoverflow.com/questions/18896535/the-better-approach-to-design-angularjs-services

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!