Evgeni
Evgeni

Reputation: 3353

Is there a way to request $http for an interceptor?

The idea is to get a data from another source in certain cases, so I have this stub:

factory("interceptor", function ($q, $location, $http) {
    return function (promise) {
        return promise;
    }
}

which fails with

[$injector:cdep] Circular dependency found: interceptor <- $http

Also tried to inject $injector and retrieve $http using that, with same results. Any ideas?

.config is nothing but declaration:

.config(function ($httpProvider) {
    $httpProvider.responseInterceptors.push('interceptor');
});

Upvotes: 5

Views: 4230

Answers (2)

Dr.Knowitall
Dr.Knowitall

Reputation: 10498

After reviewing the Angular source code the better answer is such. $http method is accessible without dependency injection so the trick is to NOT INJECT $http and to simply use it. Like such:

Right Way

retryModule = angular.module('retry-call', [])

# Do not inject $http
retryModule.factory 'RetryCall', ($q)->
  # More object keys
  'responseError': (response)=>
    # Just use $http without injecting it
    $http(response.config)
    $q.reject(response)

retryModule.config ['$httpProvider', ($httpProvider)->
    $httpProvider.interceptors.push('RetryCall');
]

Wrong Way

# Do not do it this way.
retryModule.factory 'RetryCall', ($q,$http)->

Upvotes: 1

Ilan Frumer
Ilan Frumer

Reputation: 32397

Inject $injector to interceptor:

Use it to get $http inside the returned object within callback functions.

Here is an example

app.config(function ($httpProvider) {
  $httpProvider.interceptors.push('interceptor');
});

app.factory("interceptor", function ($q, $location, $injector) {
  return {
    request: function(config){      
      var $http = $injector.get('$http');
      console.dir($http);
      return config;
    }
  }
});

app.run(function($http){
  $http.get('/')
});

Upvotes: 10

Related Questions