Blog

Differences Between Providers in AngularJS

01 Sep, 2013

AngularJSAfter reading a lot of articles and sample code it wasn’t clear to me what the difference was between the several providers like provider, factory and service. Without this knowledge you could not select the proper provider. I will explain the differences between the providers with examples.


What is a provider?

If you look at the AngularJS docs you will find the next definition of a provider:

A provider is an object with a $get() method. The injector calls the $get method to create a new instance of a service. The Provider can have additional methods which would allow for configuration of the provider.

AngularJS uses $provide to register new providers. The providers basically create new instances, but only once for each provider. The $provide has six methods to create custom providers and I will explain each one of them with the help of sample code. These providers are available on $provide:

constant

A constant can be injected everywhere. A constant can not be intercepted by a decorator, that means that the value of a constant can never be changed.

[code language=”javascript”]
var app = angular.module(‘app’, []);
app.config(function ($provide) {
$provide.constant(‘movieTitle’, ‘The Matrix’);
});
app.controller(‘ctrl’, function (movieTitle) {
expect(movieTitle).toEqual(‘The Matrix’);
});
[/code]

AngularJS provides a convenience method for creating a constant. You can rewrite the lines 3-5 to:

[code language=”javascript”]
app.constant(‘movieTitle’, ‘The Matrix’);
[/code]

value

A value is nothing more than a simple injectable value. The value can be a string, number but also a function. Value differs from constant in that value can not be injected into configurations, but it can be intercepted by decorators.

[code language=”javascript”]
var app = angular.module(‘app’, []);
app.config(function ($provide) {
$provide.value(‘movieTitle’, ‘The Matrix’)
});
app.controller(‘ctrl’, function (movieTitle) {
expect(movieTitle).toEqual(‘The Matrix’);
})
[/code]

AngularJS provides a convenience method for creating a value. You can rewrite the lines 3-5 to:

[code language=”javascript”]
app.value(‘movieTitle’, ‘The Matrix’);
[/code]

service

A service is an injectable constructor. If you want you can specify the dependencies that you need in the function. A service is a singleton and will only be created once by AngularJS. Services are a great way for communicating between controllers like sharing data.

[code language=”javascript”]
var app = angular.module(‘app’ ,[]);
app.config(function ($provide) {
$provide.service(‘movie’, function () {
this.title = ‘The Matrix’;
});
});
app.controller(‘ctrl’, function (movie) {
expect(movie.title).toEqual(‘The Matrix’);
});
[/code]

AngularJS provides a convenience method for creating a service. You can rewrite lines 3-7 to:

[code language=”javascript”]
app.service(‘movie’, function () {
this.title = ‘The Matrix’;
});
[/code]

factory

A factory is an injectable function. A factory is a lot like a service in the sense that it is a singleton and dependencies can be specified in the function. The difference between a factory and a service is that a factory injects a plain function so AngularJS will call the function and a service injects a constructor. A constructor creates a new object so new is called on a service and with a factory you can let the function return anything you want. As you will see later on, a factory is a provider with only a $get method.

[code language=”javascript”]
var app = angular.module(‘app’, []);
app.config(function ($provide) {
$provide.factory(‘movie’, function () {
return {
title: ‘The Matrix’;
}
});
});
app.controller(‘ctrl’, function (movie) {
expect(movie.title).toEqual(‘The Matrix’);
});
[/code]

AngularJS also provides a convenience method for lines 3-9. You can rewrite it to:

[code language=”javascript”]
app.factory(‘movie’, function () {
return {
title: ‘The Matrix’;
}
});
[/code]

decorator

A decorator can modify or encapsulate other providers. There is one exception and that a constant cannot be decorated.
[code language=”javascript”]
var app = angular.module(‘app’, []);
app.value(‘movieTitle’, ‘The Matrix’);
app.config(function ($provide) {
$provide.decorator(‘movieTitle’, function ($delegate) {
return $delegate + ‘ – starring Keanu Reeves’;
});
});
app.controller(‘myController’, function (movieTitle) {
expect(movieTitle).toEqual(‘The Matrix – starring Keanu Reeves’);
});
[/code]

provider

A provider is the most sophisticated method of all the providers. It allows you to have a complex creation function and configuration options. A provider is actually a configurable factory. The provider accepts an object or a constructor.

[code language=”javascript”]
var app = angular.module(‘app’, []);
app.provider(‘movie’, function () {
var version;
return {
setVersion: function (value) {
version = value;
},
$get: function () {
return {
title: ‘The Matrix’ + ‘ ‘ + version
}
}
}
});
app.config(function (movieProvider) {
movieProvider.setVersion(‘Reloaded’);
});
app.controller(‘ctrl’, function (movie) {
expect(movie.title).toEqual(‘The Matrix Reloaded’);
});
[/code]

Summary

  • All the providers are instantiated only once. That means that they are all singletons.
  • All the providers except constant can be decorated.
  • A constant is a value that can be injected everywhere. The value of a constant can never be changed.
  • A value is just a simple injectable value.
  • A service is an injectable constructor.
  • A factory is an injectable function.
  • A decorator can modify or encapsulate other providers except a constant.
  • A provider is a configurable factory.
guest
37 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Vincent
Vincent
8 years ago

The first parameter of the ‘$provide.decorator’ call must be ‘movieTitle’. No?

trackback

[…] Differences Between Providers In AngularJS […]

Miguel
Miguel
8 years ago

You’re missing a return statement in the provider example. The $get function isn’t returning.

alireza
alireza
8 years ago

Hi, I want to communicate with a RESTful Service. based on what i understand i should use provider because i need both get and set methods. Whenever I need to update something on a server i call set and whenever i want o get data from server i call get and inside this methods i will call the APIs. Am i right? or do I miss something?

trackback

[…] Differences Between Providers In AngularJS […]

trackback

[…] AngularJS中的Providers(Provide, Factory, Service)之间的区别 – Differences Between Providers In AngularJS […]

sirkitree
sirkitree
8 years ago

This is #gold. Thank you so much for writing this up.

Nicolas
Nicolas
8 years ago

Great article. Thx!

ian
ian
8 years ago

It would’ve been more helpful if you can explain when to use a provider and what problem is trying to resolve. Thanks for a good article.

ian
ian
8 years ago

What I meant was when to use a specific provider. Thanks.

Mike
Mike
8 years ago

Very nice article, however, it would be more helpful if you gave real world examples of each.
Thanks!

Francisc
Francisc
8 years ago

Nice and short, thanks.

alma
alma
8 years ago

Wow, that was really good and useful post, congrats and thanks.

semo
semo
8 years ago

super, thx!

Nick
Nick
7 years ago

This is so much better than https://docs.angularjs.org/api/auto/service/$provide
Thanks

yeyanbo
yeyanbo
7 years ago

very clear and useful!thanks

Amit
Amit
6 years ago

really nice and clear. thanks

ramanan
ramanan
6 years ago

really nice and very clear .. thanks much

Sandesh Magdum
Sandesh Magdum
6 years ago

Nice and simple to understand explanation in lucid language.
Thank you Arjan 🙂

Madan
Madan
6 years ago

That’s awesome. It saved my hell of hours. Thank you very much.

Zay Yar Phone
Zay Yar Phone
6 years ago

Thank you Sir! You should be the one writing the AngularJS Documentation. This is going to be be one of the best bookmark of the AngularJS. Hopefully we can see more of something like this for the Angular 2.0.

alencdave
alencdave
6 years ago

very good article. Lucid and very well explaining a complex topic in simple terms.
for Decorator, is it possible to write it as app.decorator(…) or we have to use $provide.decorator always?

Pavan
Pavan
6 years ago

Superb article

thathsara
thathsara
6 years ago

when i read this article it is 3 years old. author released this article on a special day of my life. yes, actually this article is so helpful to me as my birthday to understand the differences among providers. thank you!

Manik
Manik
5 years ago

Nice Article

Cassandra Blankenbeckle
Cassandra Blankenbeckle
5 years ago

Examples are the best way to learn AngularJS. Assume you already know JAVASCRIPT, then what more you required? Only Examples are good enough to get basics of AngularJS. Thanks for admin for sharing the above examples.
http://jharaphula.com

Nirupma
Nirupma
5 years ago

Nicely written article !!

Nilachal
Nilachal
5 years ago

Thanks a lot. A lot of doubts got cleared after going through the tutorial.

Sandeep
Sandeep
5 years ago

Thanks a lot. Clears out a lot of confusions. Request you to provide examples of when to use providers, when to use services and when to use factories.

prakyath
prakyath
5 years ago

Thank you so much..very clean and neat..

Ivana Juliet
4 years ago

I found it almost 4 years later!!!! the day after yesterday I running all across the internet for these codes but nothing found! Thanks for sharing with us.

ariyan usman
4 years ago

Thanks a lot. Nice article

Salman Khan
4 years ago

Very nice! Thanks

max
max
2 years ago

Great article. I loved reading this article.

Explore related posts