The Difference Between a Service And Factory in Angular JS
When I first started working with Angular 1.4.x, one of the concepts that confused me was the notion of factories, services, and providers.
My layman’s understanding of was that you can return objects and primitives from a function. By primitives, I mean things like numbers or strings.
Factories, services, and providers are concepts created specifically for the Angular framework created by Google, so I had to start researching them online.
I primarily looked at the Angular documentation and this post by Tyler McGinnis which gives a nice overview.
So what follows is my layman’s understanding of these basic concepts in Angular.
The general idea
To begin, Services, Factories, and Providers can be thought of as “Singleton” objects. A Singleton a singular reference to an object or function. The only exception to this is if a Factory returns a value. In this case, you get a value but not an object reference.
What is a Service?
The one point every blog post makes about services is that a service is instantiated with the new keyword behind the scenes. You won’t actually use the new keyword in your code as Angular does it for you.
In addition, you can add properties and methods on the this object.
Finally, the other important detail is that a Service is a special case of a Factory. I describe factories further in this post.
To give you a concrete example below is some code:
var CustomCalcService = angular
.module('CustomCalcService', [])
.service('CustomCalc', function() {
this.doubleIt = function(a) {
return 2 * a;
};
});
var customCalcApp = angular.module('customCalcApp', ['CustomCalcService']);
customCalcApp.controller('customCalcController', function($scope, CustomCalc) {
$scope.finddoubleIt = function() {
$scope.answer = CustomCalc.doubleIt($scope.number);
};
});
What is a Factory?
A factory is an object that you can add properties and utilize in your controllers. You can think of it as a function with an exposed public API.
The other important detail to note about a Factory is that it is a special case of a Provider (more on Providers later on in this post).
To give you a more concrete example here is some altered code I used in a recent side project.
The code creates a factory called AuthFactory.
var fairOfferApp = angular.module('fairOfferApp.fair_offer', ['LocalStorageModule', 'ui.bootstrap', 'ui.router', 'templates', 'restangular']);
fairOfferApp.factory('AuthFactory', ['$q', '$http', '$timeout',
function($q, $http, $timeout) {
var _identity = undefined,
_authenticated = false;
return {
isIdentityResolved: function() {
_identity = true; //this is a dummy value for the purposes of this exercise
return _identity;
}
} //end function($q, $http, $timeout)
]); //end fairOfferApp.factory...
Finally, here is an example of how you can reference the factory in your controller:
fairOfferApp.controller('loginCtrl', [
'$scope',
'$location',
'localStorageService',
'Restangular',
'AuthFactory',
function($scope, $location, localStorageService, Restangular, AuthFactory) {
console.log(AuthFactory.isIdentityResolved());
},
]);
What is a Provider?
Believe it or not, services and factories are “syntactic sugar on top of a provider recipe” according to the Angular documentation.
The first main differentiating feature of a Provider is that it implements a $get method. The other differentiating feature is that it’s the only type of “object” you can pass into the app.config portion of an Angular application.
var customCalcApp = angular.module('customCalcApp', []);
customCalcApp.provider('calcProvider', function() {
this.$get = function() {
console.log('calcProvider function $get() called.');
return 'my provider value';
};
});
customCalcApp.controller('customCalcController', function(calcProvider) {
console.log('customCalcController - calcProvider: ' + calcProvider);
//console output:
//customCalcController - calcProvider: my provider value
});
How do you know when to Use a Service, Factory, or Provider?
The best answer I found came from the aforementioned StackOverflow post which I will quote verbatim below:
Factory: The value you are providing needs to be calculated based on other data.
Service: You are returning an object with methods.
Provider: You want to be able to configure, during the config phase, the object that is going to be created before it’s created. Use the Provider mostly in the app config, before the app has fully initialized.
Personally, when just starting out with Angular, I found it easier to use a Service or Factory. I usually try to get something working and then make refinements as I learn more.
Summary
You can think of Services, Factories, and Providers as “Singleton” class objects that are special cases of each other. Factories and Services are usually the easiest to use when you’re just getting started.