0

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?

Community
  • 1
  • 1
Shamoon
  • 41,293
  • 91
  • 306
  • 570

1 Answers1

13

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

myApp.config([
  '$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push(function($q, $rootScope) {
     ...
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255