문제

I just started with Angular and I'm wondering if it's a good idea to have a base service class, and if so if this is a good way of doing it?

    var app = angular.module('UserList', ['ngResource']);

    app.service('BaseService', function() { 
        return {
            resource: '',

            setResource: function(res) {
                resource = res;
                return this;
            },

            all: function() {
                return resource.query();
            },

            find: function(id) {
                return resource.get({id: id});
            },

            save: function(user) {
                return resource.save(user)
            }
        }
    });

    app.service('UserService', ['$resource', 'BaseService', function($resource, $base) {
        var resource = $resource('/users/:id', {id: '@id'});    

        return $base.setResource(resource);
    }]);

    app.controller('UserCtrl', ['$scope', 'UserService', function($scope, User) {
        $scope.users = User.all();

        $scope.addUser = function() {
            $scope.users.push({
                first_name: $scope.user.first_name
            })

            User.save($scope.user);
        };
    }]);

My thought is that now it's super simple to add, say, a 'PostService' with a new endpoint:

    app.service('PostService', ['$resource', 'BaseService', function($resource, $base) {
        var resource = $resource('/posts/:id', {id: '@id'});    

        return $base.setResource(resource);
    }]);

If you have any comments on this approach, or any tips/recommendations regarding anything Angular (i.e. strategies, naming conventions, etc.) I'd greatly appreciate it!

Regards, Chris

도움이 되었습니까?

해결책

Does it make sense to have a base service, and if so is this a good way of doing it?

For sure its good design. Like in all Object Oriented languages its good practice to use Inheritance. The key benefit of Inheritance is that it provides the formal mechanism for code reuse. Any shared piece of business logic can be moved from the derived service into the base service as part of re-factoring process to improve maintainability of your code by avoiding code duplication.

If you have any comments on this approach, or any tips/recommendations ...

Regards to $resource documentation, the $resource('/posts/:id', {id: '@id'});, from example returns promise. Because $resource depends on $http. Not all services are async. If I have a lot of services I would sort them (or sign by adding some post-fix) that these services are async.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top