Angular: have multiple functions in one service

Is it possible to have multiple functions in one service?

I have this in my book:

(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, for example:

  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 different calls:

 BookService.get({ id: 2 }, function(book) {}) BookService.get({ name: "bookTitle" }, function(book) {}) 
+6
source share
2 answers

Yes, you can. Just define the functions inside the service. At the end, return an object that contains all the functions that you want to provide to consumers of the service. Edit: This works in factories. For services, see Nathan Response.

 (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 }; } })() 
+4
source

When using the service, you can attach functions to this . This way you can have several functions in one service. eg:

 (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 } }); } })() 

Then you can access the functions with BookService.fun1() and Bookservice.fun2()

If you attach functions to an object and then return this object as fikkatra does, then use factory instead of service.

+4
source

All Articles