AngularJS - what are the major differences in the different ways to declare a service in angular?

14,669

I would suggest you layout your factory or service as they do in the angular-seed app, except that app annoyingly only uses value in the services.js boilerplate. However you can adapt the layout they use for controllers, directives and filters.

'use strict';

/* Filters */

angular.module('myApp.filters', []).
  filter('interpolate', ['version', function(version) {
    return function(text) {
      return String(text).replace(/\%VERSION\%/mg, version);
    }
  }]);

Which means for a service you would do:

'use strict';

/* Services */

angular.module('myApp.filters', []).
  service('myservice', ['provider1', 'provider2', function(provider1, provider2) {
      this.foo = function() { 
          return 'foo'; 
      };
  }]).
  factory('myfactoryprovider', ['myservice', function(myservice) {
       return "whatever";
  }]);

This has more boilerplate than you absolutely need, but it is minification safe and keeps your namespaces clean.

Than all you have to do is decide which of const, value, factory or service is most appropriate. Use service if you want to create a single object: it gets called as a constructor so you just assign any methods to this and everything will share the same object. Use factory if you want full control over whether or not an object is created though it is still only called once. Use value to return a simple value, use const for values you can use within config.

Share:
14,669
Georgi Angelov
Author by

Georgi Angelov

Updated on June 28, 2022

Comments

  • Georgi Angelov
    Georgi Angelov about 2 years

    I am working on an angularJS app and I am trying to stick with the most efficient and widely accepted styles of development in AngularJs. Currently, I am using this way of declaring my services like so:

    app.factory('MyService', function() {
      /* ... */
      function doSomething(){
         console.log('I just did something');
    
      }
    
      function iAmNotVisible(){
          console.log('I am not accessible from the outside');
      }
      /* ... */
    
      return{
         doSomething: doSomething
      };
    });
    

    However, there are numerous examples out there and I am not quite sure which design style to follow. Can someone with extensive knowledge about services explain the reason why a certain style is more relevant than another?

    Is what I am doing useful in any way other than restricting the access to certain functions in my service?