5

I have been using angular for a good while and I have read lots of information on the differences between using .service(...) and .factory(...) in angular, the main point being that .service() instantiates and instance of an object for you. But I have yet to read why this is of any use because .service(...) gives you the same instance everytime you use it.

So what is the point of even having this function in angular when every instance is the same - why not just use factory(...) and remove service() from the framework? I don't understand why they even have a function that instantiates object instances if you can only ever have one instance?

csss
  • 1,937
  • 2
  • 14
  • 24
  • 1
    They all do the same thing but provide different levels of control. Check out the answer here: http://stackoverflow.com/questions/15666048/angular-js-service-vs-provide-vs-factory – Will M Jul 20 '13 at 17:58
  • I have read that post and many others like it. It still seems pointless to have a function that instantiates instances when it always returns the same instance. It defeats the entire reason for having instances of objects. So there is no reason to use it as far as I can see. – csss Jul 20 '13 at 18:26
  • For the difference between a service and a factory: one returns an instance of an object which is the function that you pass as the argument to the service method, the factory returns whatever the results are from execution the function. They are 100% not the same thing. They are all aliases in some way for using $provider from what I understand, but having convenient ways to do things differently is not a problem. – shaunhusain Jul 20 '13 at 18:57
  • @shaunhusain Please explain what is the point of returning an instance of an object when every instance service() returns is the same instance. This defeats the point of instances does it not? – csss Jul 20 '13 at 19:10
  • 1
    This doesn't mean you remove the ability to create instances from a language. In the case of a factory you can choose to create a new object that you return in your factory function. In a service you get a singleton, which is to say you get a built in design pattern, the same instance will always be accessible with the same name, this allows the instance to be shared by multiple parts of the application. If instead you want different instances perhaps a factory is really what you're looking for. Also thanks for keeping it civil. – shaunhusain Jul 20 '13 at 19:14

0 Answers0