The better approach to design AngularJS services

2019-03-13 11: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
2楼-- · 2019-03-13 11:26

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});
查看更多
登录 后发表回答