I am using a service
where there should be a factory
and I don't get an error.
My service returns and object when it should return a constructor function.
But my code works perfectly.
for example, the code below should not work. But it works fine:
angular.module('myApp', [])
.service('myService', myService);
function myService(/*<dependencies go in here>*/){
return {
/*<object attributes in here>*/
}
}
The correct code should be this:
angular.module('myApp', [])
.factory('myService', myService);
function myService(/*<dependencies go in here>*/){
return {
/*<object attributes in here>*/
}
}
My question is why angular allows you to use a .service
when you are actually returning an object and should be using .factory
OK This is my answer for this interesting question.
First of all lets make sure we understand the main difference between service and factory, it will be easier after we see both implementations:
Factory:
function factory(name, factoryFn) {
return provider(name, { $get: factoryFn });
}
Service:
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
As we can see what factory actually is doing is getting us the object the factory functions returns.
Service in the other hand instantiates a new object using the constructor function we provided. Needless to say both are singletons.
In your example above the factory is used just like it should be, thats the best practice. I guess the interesting part is why the service is working while his constructor function doesn't really defines a class but returns an object as well.
Here comes the tricky part, it is working because as said before using the service actually instantiate an object, in our bad practice we override the default constructor with new constructor.
Sounds confusing? here is a Fiddle that performs basically the same thing, we use new ConstructorFunc() while the ConstructorFunc() instead of defining an object and create its properties using this.prop=something is returning an object.
Maybe it is not a best practice but it is possible. I think we better keep working with service as we used to for following the convention.
Interesting article factory vs service vs provider
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With