What is the difference between a service, a factory and a provider in AngularJS?

AngularJS Services & DI Intermediate 2–3 Yrs3–5 Yrs Conceptual 1 min read

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) — fn returns whatever you want (object, function, primitive). Under the hood everything else is built on this.
  • service('x', Ctor) — Angular does new Ctor(); you attach members to this. Just syntactic preference over factory.
  • provider('x', {...}) — the only one available during config(), so it's how you'd let an app set an API base URL or a feature flag before startup. Its $get is the factory.
  • value and constant are simpler forms for plain data (constant is also available in config).