是否可以在一项服务中具有多种功能?
我的图书服务中有这个:
(function() {
'use strict';
angular
.module('app.core')
.service('BookService', BookService);
BookService.$inject = ['$resource'];
/* @ngInject */
function BookService($resource) {
return $resource('/api/book/:id', {
id: '@id'
}, {
'get': {
method: 'GET',
cache: true
},
'query': {
method: 'GET',
isArray: true,
cache: true
},
});
}
})()
但在同一个服务中,我想要另一个函数,我将传递其他参数,例如:
return $resource('/api/book/:name', {
name: '@name'
}, {
'get': {
method: 'GET',
cache: true
},
'query': {
method: 'GET',
isArray: true,
cache: true
},
});
我的 Controller 看起来像这样并且有两个不同的调用:
BookService.get({
id: 2
}, function(book) {})
BookService.get({
name: "bookTitle"
}, function(book) {})
最佳答案
是的你可以。只需定义服务中的功能。最后,返回一个对象,其中包含您要向服务的使用者公开的所有函数。编辑:这适用于工厂。有关服务,请参阅 nathan 的回答。
(function() {
'use strict';
angular
.module('app.core')
.factory('BookService', BookService);
BookService.$inject = ['$resource'];
/* @ngInject */
function BookService($resource) {
var getById = function(id){
return $resource('/api/book/:id', {
id: id
}, {
'get': {
method: 'GET',
cache: true
}
});
};
var getByName = function(name) {
return $resource('/api/book/:name', {
name: name
}, {
'get': {
method: 'GET',
cache: true
}
});
};
return {
getById: getById,
getByName: getByName
};
}
})()
关于angularjs - Angular : Have multiple functions in one Service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36655564/