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

后端 未结 2 996
后悔当初
后悔当初 2020-12-10 19:41

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 fu         


        
相关标签:
2条回答
  • 2020-12-10 19:57

    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)->
    
    0 讨论(0)
  • 2020-12-10 19:58

    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('/')
    });
    
    0 讨论(0)
提交回复
热议问题