Understanding AngularJS service types

Updated . Posted . Visible to the public.

Angular comes with different types of services. Each one with its own use cases.

All of these services are singletons. You probably want to use Factory all the time.

Provider

  • is the parent of all other services (except constant)
  • can be configured using `app.config(function(Provider) { ...})
  • a little complex

Factory

  • simpler than Provider, but without configuration
  • definition: `app.factory('name', someFunction)
  • someFunction is called when the name service is instantiated and should return an object

Service

  • just like Factory, but:
  • instead of a funciton, it receives a Javascript class / a constructor function as argument
  • simplest service type, but also least flexible

Value

  • just stores a single value
  • use it like `app.value('name', 'value')

Constant

  • just like value, but:
  • can be injected everywhere
  • is not constant Oo, but may be changed

Decorating services

  • useful for extending 3rd-party services
  • $delegate is the service instance
    ^
app.config(function($provide) {
  $provide.decorator('serviceToBeDecorated', function($delegate) {
    // modify $delegate by adding functions etc.
    return $delegate;
  });
});

More differences

| | Factory | Service | Value | Constant | Provider |
| can have dependencies | yes | yes | no | no | yes |
| uses type friendly injection | no | yes | yes* | yes* | no |
| object available in config phase | no | no | no | yes | yes** |
| can create functions | yes | yes | yes | yes | yes |
| can create primitives | yes | no | yes | yes | yes |

(taken from Angular Guide Show archive.org snapshot . Go there for further explanation.)

Henning Koch
Last edit
Judith Roth
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2013-09-16 09:40)