When we start creating an angular js app, there are many modules and functions which doubts us which one to use and whereThe major ones are services, factories and providersThey both seems like so similar in angularjs and lets go ahead and work around some code examples which clearly mention the correct ways.
This shows how the CarService will always a produce a car with 4 cylinders, you can't change it for individual cars. Whereas CarFactory returns a function so you can do
new CarFactory
in your controller, passing in a number of cylinders specific to that car. You can't do new CarService
because CarService is an object not a function.
The reason factories don't work like this:
app.factory('CarFactory', function(numCylinder) {
this.dealer="Bad";
this.numCylinder = numCylinder
});
| Type | Singleton| Instantiable | Configurable|
| Factory | Yes | No | No |
| Service | Yes | Yes | No |
| Provider| Yes | Yes | Yes |
---------------------------------------------------
app.factory('CarFactory', function() {
function Car(numCylinder) {
this.delaer="Bad";
this.numCylinder = numCylinder
};
Car.prototype.breakCylinder = function() {
this.numCylinder -= 1;
};
return Car;
});
---------------------------------------------------
---------------------------------------------------
---------------------------------------------------
---------------------------------------------------
app.factory('CarFactory', function() {
return {
numCylinder: 4
};
});
app.service('CarService', function() {
this.numCylinder = 4;
});
And automatically return a function for you to instantiate, is because then you can't do this (add things to the prototype/etc):
See how it is literally a factory producing a car.
The conclusion from his blog is pretty good:
In conclusion,
Use Factory when you need just a simple object such as a Hash, for example {foo;1, bar:2} It’s easy to code, but you cannot instantiate it. Use Service when you need to instantiate an object, i.e new Customer(), new Comment(), etc. Use Provider when you need to configure it. i.e. test url, QA url, production url.
If you find you're just returning an object in factory you should probably use service.
Don't do this:
Use service instead:
No comments:
Post a Comment