3

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.

0

3 Answers 3

4

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') }
      })}
Sign up to request clarification or add additional context in comments.

Comments

1

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({...});
             }
           })
         }])

1 Comment

Maybe for other services, but injecting the service inside its provider gives me an error Circular dependency found: $http <- $http <- $templateFactory <- $view <- $state
0

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.