是否可以在一个服务中拥有多个功能?
我的书服务中有这个:
(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
},
});
}
})()
Run Code Online (Sandbox Code Playgroud)
但是在同一个服务中,我希望有另一个功能,我将传递其他参数,例如:
return $resource('/api/book/:name', {
name: '@name'
}, {
'get': {
method: 'GET',
cache: true
},
'query': {
method: 'GET',
isArray: true,
cache: true
},
});
Run Code Online (Sandbox Code Playgroud)
我的控制器看起来像这样,有两个不同的调用:
BookService.get({
id: 2
}, function(book) {})
BookService.get({
name: "bookTitle"
}, function(book) {})
Run Code Online (Sandbox Code Playgroud)
是的你可以。只需定义服务中的功能。最后,返回一个对象,其中包含您要向服务的使用者公开的所有函数。编辑:这适用于工厂。有关服务,请参阅 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
};
}
})()
Run Code Online (Sandbox Code Playgroud)
使用服务时,您可以将功能附加到this. 这样您就可以在一项服务中拥有多种功能。例如:
(function() {
'use strict';
angular
.module('app.core')
.service('BookService', BookService);
BookService.$inject = ['$resource'];
/* @ngInject */
function BookService($resource) {
this.fun1 = function(){
return $resource('/api/book/:id', {
id: '@id'
}, {
'get': {
method: 'GET',
cache: true
}
});
}
this.fun2 = function(){
return $resource('/api/book/:name', {
name: '@name'
}, {
'get': {
method: 'GET',
cache: true
}
});
}
})()
Run Code Online (Sandbox Code Playgroud)
BookService.fun1()然后您可以使用和访问这些功能Bookservice.fun2()
如果将函数附加到一个对象,然后以 fikkatra 的方式返回该对象更有意义,那么使用工厂而不是服务。
| 归档时间: |
|
| 查看次数: |
5572 次 |
| 最近记录: |