Reputation: 113
I’m trying to understand what the essential differences between service and factory are (in AngularJS). Is it true to say that a factory is a singleton and a service is a new object every time you call it?
Upvotes: 2
Views: 58
Reputation: 52867
In javascript, functions can resemble a class which has instance variables, instance methods, and can be new'ed up:
// creating a class Box
function Box(col)
{
// instance member variable color, default to 'Red' if no color passed
var color = col || 'Red';
// instance method
this.getColor = function()
{
return color;
}
}
To instantiate a Box, and initialize it with different colors:
var blueBox = new Box("blue");
alert(blueBox.getColor()); // will alert blue
var greenBox = new Box("green");
alert(greenBox.getColor()); // will alert green
An angular service is used to register constructor functions like the Box example. When the service is injected, an instance of the service is passed into your function:
// declare a service
app.service('box', Box);
// inject instance of Box into controller: 'box' is a new Box()
app.controller('ctrl', function(box) {
alert(box.getColor()); // alerts 'Red'
});
In contrast, an angular factory does not return an instance of a function. Instead, it caches and returns the result of invoking the function:
// declare a factory
app.factory('user', function() {
// return an object literal
return {
name: 'john',
}
});
app.controller('ctrl', function(user) {
alert(user.name);// user is the object literal which was returned from the user factory.
};
Think of factories as a way of returning the result of a function; the result is a singleton an shared between all injections.
Think of services as a way of instantiating classes (or function constructors); the instance is also a singleton and shared between all injections.
Both factories and services are singletons.
Upvotes: 1
Reputation: 20155
the only difference between services and factories is that services are called with new
stuffToInject = new Service();
whereas factories are just called like functions
stuffToInject = Factory();
Otherwise it's the same,both Factories and Services are singleton.The only question you need to ask yourself is does my Service needs the new operator or not.If not ,use module.factory
,else module.service
.
exemple:
function(){
this.foo=function(){
}
}
needs to be registered with module.service
function(){
return {
foo:function(){}
};
}
can be registered with module.factory
Upvotes: 1