1

I am very newbie to AngularJS and sorry if it is a basic question.

I know that the services and factories are used for doing almost the same thing. They are used to get the external data.

But, is there any use case where we should use both in the same angular module? Just curious, as I was going through one of the github projects and realized they were using both services and factories for the same module. What is the advantage of doing it?

SomeUiDev
  • 43
  • 5

2 Answers2

0

There's no practical difference, unless you prefer typing one way over another. I typically use services because I enjoy writing

this.myFunk = function(){...}

more than

myFunk: function(){....}

Whichever you prefer typing is the best way.

This is a great read that will clarify some of the differences between factories, services, and providers (which DO have different use cases than factories and services):

http://tylermcginnis.com/angularjs-factory-vs-service-vs-provider/

Sorry, just re-read your question. As far as I'm aware, there's no practical reason to use both in one module, as they accomplish the same thing. The only reason I can think for not using both services and factories in the same module is consistency in your code.

Jacob Turner
  • 1,691
  • 1
  • 11
  • 15
  • 1
    Though, I understood what you are saying, I didn't get why there are 3 different things to do the same thing. – SomeUiDev Oct 30 '14 at 16:16
0

I think they originally wanted to make both those who like to new things and those who don't happy.

Personally we go with .factory() and like to use the Revealing Module Pattern to make it easy to see what methods / properties are available from that service/factory at a glance.

https://github.com/johnpapa/angularjs-styleguide#factories

this can end up with having to scroll all over trying to find what you can call from that "service"

/* avoid */
function dataService() {
  var someValue = '';
  function save() { 
    /* */
  };
  function validate() { 
    /* */
  };

  return {
      save: save,
      someValue: someValue,
      validate: validate
  };
}

instead use this

/* recommended */
function dataService() {
    var someValue = '';
    var service = {
        save: save,
        someValue: someValue,
        validate: validate
    };
    return service;

    ////////////

    function save() { 
        /* */
    };

    function validate() { 
        /* */
    };
}
John
  • 6,503
  • 3
  • 37
  • 58