Differences Between Providers in AngularJS
After 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.
Comments
The first parameter of the ‘$provide.decorator’ call must be ‘movieTitle’. No?
Thank you for pointing out the typo. I have changed it to ‘movieTitle’.
[…] Differences Between Providers In AngularJS […]
You’re missing a return statement in the provider example. The $get function isn’t returning.
Thanks! I’ve already corrected it.
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?
[…] Differences Between Providers In AngularJS […]
[…] AngularJSä¸Providers之间的差异 […]
[…] AngularJSä¸çš„Providers(Provide, Factory, Service)之间的区别 – Differences Between Providers In AngularJS […]
This is #gold. Thank you so much for writing this up.
Great article. Thx!
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.
What I meant was when to use a specific provider. Thanks.
Very nice article, however, it would be more helpful if you gave real world examples of each.
Thanks!
Nice and short, thanks.
Wow, that was really good and useful post, congrats and thanks.
super, thx!
This is so much better than https://docs.angularjs.org/api/auto/service/$provide
Thanks
very clear and usefulï¼thanks
really nice and clear. thanks
really nice and very clear .. thanks much
Nice and simple to understand explanation in lucid language.
Thank you Arjan 🙂
That’s awesome. It saved my hell of hours. Thank you very much.
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.
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?
Superb article
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!
Nice Article
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
Nicely written article !!
Thanks a lot. A lot of doubts got cleared after going through the tutorial.
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.
Thank you so much..very clean and neat..
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.
Thanks a lot. Nice article
Very nice! Thanks
Great article. I loved reading this article.