Search This Blog

Tuesday 19 May 2015

Service vs provider vs factory vs Value vs Constant in angularjs

All Services are singletons; they get instantiated once per app. They can be of any type, whether it be a primitive, object literal, function, or even an instance of a custom type.
The valuefactoryserviceconstant, and provider methods are all providers. They teach the Injector how to instantiate the Services.
The most verbose, but also the most comprehensive one is a Provider recipe. The remaining four recipe types — Value, Factory, Service and Constant — are just syntactic sugar on top of a provider recipe.
  • The Value Recipe is the simplest case, where you instantiate the Service yourself and provide the instantiated value to the injector.
  • The Factory recipe gives the Injector a factory function that it calls when it needs to instantiate the service. When called, the factory function creates and returns the service instance. The dependencies of the Service are injected as the functions' arguments. So using this recipe adds the following abilities:
    • Ability to use other services (have dependencies)
    • Service initialization
    • Delayed/lazy initialization
  • The Service recipe is almost the same as the Factory recipe, but here the Injector invokes aconstructor with the new operator instead of a factory function.
  • The Provider recipe is usually overkill. It adds one more layer of indirection by allowing you to configure the creation of the factory.
    You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to vary slightly between applications.
  • The Constant recipe is just like the Value recipe except it allows you to define services that are available in the config phase. Sooner than services created using the Value recipe. Unlike Values, they cannot be decorated using decorator.