The better approach to design AngularJS services

前端 未结 1 1913
无人共我
无人共我 2021-02-04 16:49

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. Actu

相关标签:
1条回答
  • 2021-02-04 17:32

    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});
    
    0 讨论(0)
提交回复
热议问题