我刚开始使用 Angular,我想知道拥有一个基本服务类是否是个好主意,如果是这样,这是否是一种好方法?
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);
};
}]);
我的想法是,现在添加一个带有新端点的“PostService”非常简单:
app.service('PostService', ['$resource', 'BaseService', function($resource, $base) {
var resource = $resource('/posts/:id', {id: '@id'});
return $base.setResource(resource);
}]);
如果您对这种方法有任何意见,或者对任何 Angular(即策略、命名约定等)有任何提示/建议,我将不胜感激!
问候,克里斯