Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using angular factories and services interchangeably - no error

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

like image 693
raneshu Avatar asked Mar 17 '23 00:03

raneshu


1 Answers

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

like image 200
Or Guz Avatar answered Apr 25 '23 06:04

Or Guz