Roadmap › AngularJS (1.x) — Legacy › Module: Services and Dependency Injection
Lessons in this course (13)

6. Service vs factory vs provider vs value vs constant

Intermediate★ Must knowLesson 6 of 13

All create singletons registered with the injector.

js
const app = angular.module("shopApp", []);

app.constant("API_URL", "/api");                       // available in config blocks
app.value("pageSize", 20);                              // simple value (not in config)

app.factory("orderApi", function ($http, API_URL) {     // factory: returns an object you build
  return {
    list: () => $http.get(`${API_URL}/orders`).then(r => r.data),
    save: order => $http.post(`${API_URL}/orders`, order).then(r => r.data),
  };
});

app.service("cart", function () {                       // service: constructor function, called with 'new'
  this.items = [];
  this.add = item => this.items.push(item);
});

app.provider("theme", function () {                     // provider: configurable before the app runs
  let color = "blue";
  this.setColor = c => (color = c);                     // used in config()
  this.$get = () => ({ color: () => color });           // the actual service
});
app.config(themeProvider => themeProvider.setColor("green"));
Registered withInjectable in config?Use
constantvalueYesSettings needed during config
valuevalueNoSimple values
factoryfunction returning an objectNoMost common for logic/API wrappers
serviceconstructor (new)NoClass-style services
providerobject with $getProvider yes, service noConfigurable reusable services