What is the difference between a service, a factory and a provider in AngularJS?
Quick Answer
All three register an injectable singleton; they differ in how you define it. factory — a function that returns the object (most common, flexible). service — a constructor function that Angular news (returns this). provider — the most configurable; has a $get and can be configured in the config() phase before the app runs.
They all give you an injectable singleton — the difference is the recipe. A factory is a function that returns the thing, and it's the most common because you can return anything. A service is a constructor that Angular calls with new, so you hang everything off this — it's really just a style choice over factory. A provider is the fully configurable version: it has a $get method and, importantly, it's the only one you can configure in the config phase, before the app bootstraps, which is how you'd inject an environment-specific base URL. Under the hood factory and service are both implemented as providers.
factory('x', fn)—fnreturns whatever you want (object, function, primitive). Under the hood everything else is built on this.service('x', Ctor)— Angular doesnew Ctor(); you attach members tothis. Just syntactic preference over factory.provider('x', {...})— the only one available duringconfig(), so it's how you'd let an app set an API base URL or a feature flag before startup. Its$getis the factory.valueandconstantare simpler forms for plain data (constantis also available inconfig).