Hacker News new | ask | show | jobs
by minznerjosh 4421 days ago
That can be a matter of personal preference, so the best I can do is share my preference.

I usually use the "service" method because most of my services are objects, and I have no aversion to constructor functions.

However, if I want my service to be a function (a la $http or $timeout,) I'll use a factory (because I don't want a constructor to be new-ed, I just want to create a function.)

And, as the article states, I'd use a provider if I want to provide methods to configure my service before it is instantiated.

I think a lot of it comes down to semantics. Maybe it's just me, but describing my object via a constructor function (as a "service") makes it feel a bit weightier than creating and returning a POJO in a factory. But, from a practical standpoint, you can see it as this:

A provider is responsible for creating (providing) an injectable (as a singleton) object that others can request to be injected. The provider creates this object in its $get method. It can also have methods/properties other than $get that can be called/modified in the config stage to configure the object it will create.

But, often times (maybe the majority of times,) you don't need to configure your injectable before it is created, so we really only care about the $get method of the provider. This is where the "factory" API comes in. It just eliminates all the boilerplate around creating a provider that only has a $get method.

And finally, for reasons that are not entirely clear to me, the angular team also decided to provide a shorthand for creating a constructor, and returning a new instance of that constructor in the $get method of the provider (or the factory function if you like.) And that's what the "service" API is.

So, the provider is the root API, factory is sugar on top of the provider API, and service is sugar on top of factory API.