zelinka
zelinka

Reputation: 3413

Inject http into httpProvider in AngularJS

I want to make it so that users are automatically logged out by having the client terminate the session (as opposed to letting the session die on its own). I pushed an interceptor onto the $httpProvider which allows me to set and reset the timeout timer, but the problem is that I can't figure out how to call the logout function which requires $http. This always produces a circular dependency. Is there any way to do this?

app.config(['$httpProvider', function($httpProvider) {
  $httpProvider.interceptors.push(
    function() {
      return {
        response: function(response) { $http({ ... }); }
      })}

If I make $http a dependency, I get a circular dependency, but without the $http dependency, the call to $http obviously doesn't work.

Upvotes: 3

Views: 4615

Answers (3)

dlauzon
dlauzon

Reputation: 1321

I used a crossover of the previous answers (use $injector, but in the push() ) to get it working as expected:

app.config(['$httpProvider', function($httpProvider) {

  $httpProvider.interceptors.push(function($q, $injector) {
      ...
      //now get $http like this and use it as needed:
      $injector.get('$http')

Upvotes: 0

jfadich
jfadich

Reputation: 6348

You should be careful using $http inside an interceptor as it has the potential to cause an infinite loop. Consider refactoring so $http isn't required

That said you can try injecting the $injector instead. Then where you want to make the $http request just use $injector.get('$http')

app.config(['$httpProvider, $injector', function($httpProvider, $injector) {
  $httpProvider.interceptors.push(
    function() {
      return {
        response: function(response) { $injector.get('$http') }
      })}

Upvotes: 4

Pankaj Parkar
Pankaj Parkar

Reputation: 136164

You need to inject $http dependancy inside theinceptor.push function, you could also inject other dependencies from there.

Code

app.config(['$httpProvider',
    function($httpProvider) {
       $httpProvider.interceptors.push(
         function($http) { //<--here you could make dependency available.
           return {
             response: function(response) {
               $http({...});
             }
           })
         }])

Upvotes: 1

Related Questions