Difference between a service and a factory in Angular
Aditya Bhushan Chaturvedi
Assistant Manager @EY, Previous Technology Specialist @Coforge
Kindly first refer to image before going in depth
In Angular difference between a Service and a Factory:
Service:
1. By default returns object and not constructor function
2. So that's why constructor function is set to this.model property.
3. If you use a service you will get the instance of a function ("this" keyword).
4. You just instantiated with the ‘new’ keyword and you will add properties to ‘this’ and the service will return ‘this’.
5. Could be useful for sharing utility functions that are useful to invoke by simply appending () to the injected function reference.
6. If you're using a class you could use the service provider.
7. You can add properties and functions to a service object by using the this keyword
Factory:
1. By default returns constructor function and not object .
2. So that's why new object can be created with constructor function.
3. If you use a factory you will get the value that is returned by invoking the function reference (the return statement in factory).
4. In common way AngularJS should use factory. Because "The factory method is the most common way of getting objects into AngularJS dependency injection system. It is very flexible and can contain sophisticated creation logic. This is very useful as we can hide implementation details of a given service."
5. Could be useful for returning a ‘class’ function, means use a factory when you have complex logic in your service and you don't want expose this complexity.
6. If you're using an object, you could use the factory provider.
7. Can use other dependencies.
Major Difference:
1. As per angular docs, service recipe works better for objects of custom type, while Factory can produce JavaScript primitives and functions.
2. Syntax:
A. Service:
app.controller('AppController', function (MyService) {
MyService.sayHello(); // logs 'hello'
});
B. Factory:
app.factory('MyService', function () {
return {
sayHello: function () {
console.log('hello');
}
}
});
Few Common things in Service and Factory:
1. There won't be any performance hit , using Service or Factory.
2. Both are singleton objects and only one instance is created per app.
3. Being only one instance every where their reference is passed.
4. Using one or the other (service or factory) is about code style.
Azure (AZ-104, AZ-305) | former Angular/NgRx Developer/Architect at Capgemini
7 年Angular 2 & 4 is sooo much simpler. And more efficient. And compile-time checking of your variables.