Shamoon Shamoon - 2 months ago 12
AngularJS Question

Issue getting $rootScope injected into config of Angular?

I am doing:

myApp.config([
'$httpProvider', '$rootScope', function($httpProvider, $rootScope) {
$httpProvider.interceptors.push(function($q) {
return {
responseError: function(rejection) {
var defer;
defer = $q.defer();
if (rejection.status === 401) {
$rootScope.$broadcast('api-error', rejection);
}
defer.reject(rejection);
return defer.promise;
},
response: function(response) {
var defer;
defer = $q.defer();
console.log(response);
if (response.status === 401) {
$rootScope.$broadcast('api-error', response);
defer.reject(response);
} else {
defer.resolve(response);
}
return defer.promise;
}
};
});
}
]);


But I get an error that it cannot find
$rootScope
. I read this answer and it says to do some weird global variable stuff, which seems like a bad idea.
So how can I redirect to another route upon a 401 status?

Answer

Inject $rootScope in the interceptor, not in the configuration function:

myApp.config([
  '$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push(function($q, $rootScope) {
     ...