Roadmap › AngularJS (1.x) — Legacy › Module: Services and Dependency Injection
Lessons in this course (13)
8. $http, promises and $q
Intermediate★ Must knowLesson 8 of 13
js
app.factory("productApi", ["$http", "$q", function ($http, $q) {
const cache = {};
return {
get(id) {
if (cache[id]) return $q.resolve(cache[id]); // $q promise, integrates with the digest
return $http.get(`/api/products/${id}`, { timeout: 10000 })
.then(res => (cache[id] = res.data))
.catch(err => $q.reject(err.status === 404 ? "Not found" : "Server error"));
},
all: ids => $q.all(ids.map(id => this.get(id))),
};
}]);
// Interceptor: add auth header and handle 401 globally
app.factory("authInterceptor", ["$q", "$window", function ($q, $window) {
return {
request: config => { config.headers.Authorization = `Bearer ${$window.sessionStorage.token}`; return config; },
responseError: rejection => { if (rejection.status === 401) $window.location = "/login"; return $q.reject(rejection); },
};
}]);
app.config(["$httpProvider", $httpProvider => $httpProvider.interceptors.push("authInterceptor")]);$http's .success()/.error() were removed in 1.6 — use .then(). Use $q, $timeout, $interval (not native promises/setTimeout) so changes trigger a digest — or call $scope.$applyAsync().