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 with | Injectable in config? | Use | |
|---|---|---|---|
| constant | value | Yes | Settings needed during config |
| value | value | No | Simple values |
| factory | function returning an object | No | Most common for logic/API wrappers |
| service | constructor (new) | No | Class-style services |
| provider | object with $get | Provider yes, service no | Configurable reusable services |