Shane
Shane

Reputation: 5667

AngularJS provider function

function provider(name, provider_) {
  assertNotHasOwnProperty(name, 'service');
  if (isFunction(provider_) || isArray(provider_)) {
    provider_ = providerInjector.instantiate(provider_);
  }
  if (!provider_.$get) {
    throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  }
  return providerCache[name + providerSuffix] = provider_;
}

https://github.com/angular/angular.js/blob/master/src/auto/injector.js#L655-680

I was actually looking at the provider function of injector.js, it seems that all the services[constant, value, factory, service and provider itself] is a mere wrapper of the provider.

Can anyone help me in understanding these questions:

  1. Why are all these a wrapper of provider? Let's take i have a factory/service named "Shane", why would i pass it to a provider to create the "Shane" Object?
  2. Why is there a provider/service then?

Upvotes: 0

Views: 184

Answers (1)

just-boris
just-boris

Reputation: 9746

Factories, services, and others is a just useful wrappers for provider. Provider request so much code to be written:

 angular.module('app', []).provider('myProvider', function(/*here you can inject another providers*/) {
     // this function can be called by another providers
     this.config = function() {}; 
     this.$get = function(/*here you can inject services*/) {
          // exprort your service value
          return {};
     };
 });

This is how providers work:

  1. First of all, providers can interact with each other and by calling methods like in example above.
  2. Then all the $get methods are being called from all providers. This function accept other services as arguments, so here you can interact with some services.
  3. The result of $get method is an actual value of your service which can be injected into another services, controllers, etc.

If your service don't need all of this features, you can skip some first steps and start from any further. If you don't need to work with providers, use factory. If you even don't need to use services, use service (which works as usual js-constructor function) or value if your service actually a static value and doesn't require extra preparations.

Look at the $provide documentation to know about exact API of all of these registering functions.

Upvotes: 2

Related Questions