The better approach to design AngularJS services

All we need is an easy explanation of the problem, so here it is.

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?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

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

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply