AngularJS: Service vs Factory vs Provider

From the Angular mailing list I got an amazing thread that explains service vs factory vs provider and their injection usage. compiling the answers:

Services

Syntax: module.service( 'serviceName', function );
Result: When declaring serviceName as an injectable argument you will be provided with an instance of the function. In other words new FunctionYouPassedToService().

Factories

Syntax: module.factory( 'factoryName', function );
Result: When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.

Providers

Syntax: module.provider( 'providerName', function );
Result: When declaring providerName as an injectable argument you will be provided with new ProviderFunction().$get(). The constructor function is instantiated before the $get method is called – ProviderFunction is the function reference passed to module.provider.

Providers have the advantage that they can be configured during the module configuration phase.

see here for the provided code: http://jsbin.com/ohamub/1/edit

Result from output:


“Hello World” example with factory / service / provider:

http://jsfiddle.net/pkozlowski_opensource/PxdSP/14/

Result from output:


And here’s a great further explanation by Misko:

But that is way too wordy and a shorter way to write this would be provider.service('greeter', Greeter); .But what if we wanted to configure the Greeter class before the injection then we could write

But it turns out that angular only understands $provide.provider, all other ones are derived.

Resource: Stackoverflow

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA