Is it possible to have multiple functions in one service ?
I have this in my book service :
(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
},
});
}
})()
But in the same service i want to have another function where i will pass other parameters, ex :
return $resource('/api/book/:name', {
name: '@name'
}, {
'get': {
method: 'GET',
cache: true
},
'query': {
method: 'GET',
isArray: true,
cache: true
},
});
My controller looks like this and has two differents calls:
BookService.get({
id: 2
}, function(book) {})
BookService.get({
name: "bookTitle"
}, function(book) {})
Yes you can. Just define the functions within the service. At the end, return an object that contains all the functions you want to expose to the consumers of the service. Edit: this works for factories. For services, see nathan's answer.
When using a service you can attach functions to
this
. In that way you can have multiple functions in one service. for example:You can then access the functions with
BookService.fun1()
andBookservice.fun2()
If attaching the functions to an object and then returning that object in the way that fikkatra did makes more sense, then use a factory instead of a service.