inject $route into a http interceptor

情到浓时终转凉″ 提交于 2019-12-05 00:16:59

问题


I am trying to inject custom header to every API request. When I am providing some hard coded text it works.

Working code

myApp.config(['$httpProvider', function ($httpProvider) {
    var requestInterceptor = ['$q', '$rootScope', 
        function ($q, $rootScope) {
            var interceptorInstance = {
                request: function (config) {
                    config.headers['X-MyApp-CustomHeader'] = "foobar"; 
                    return config || $q.when(config);
                }
            };
            return interceptorInstance;
        }];

    $httpProvider.interceptors.push(requestInterceptor);
}]);

Not working code

myApp.config(['$httpProvider', function ($httpProvider) {
    var requestInterceptor = ['$q', '$rootScope', '$route',
        function ($q, $rootScope, $route ) {
            var interceptorInstance = {
                request: function (config) {
                    config.headers['X-MyApp-CustomHeader'] = $route.current.params.CustomParameter; 
                    return config || $q.when(config);
                }
            };
            return interceptorInstance;
        }];

    $httpProvider.interceptors.push(requestInterceptor);
}]);

Error, When trying to inject $route

Uncaught Error: [$injector:cdep] Circular dependency found: $route <- $http http://errors.angularjs.org/1.2.3/$injector/cdep?p0=%24route%20%3C-%20%24http


回答1:


This is a known issue.

Check out my answer: Is there a way to request $http for an interceptor?

$route depends on $http which in turn depends on the interceptors:

myApp.config(['$httpProvider', function ($httpProvider) {
    var requestInterceptor = ['$q', '$rootScope', '$injector',
        function ( $q, $rootScope, $injector ) {
            var interceptorInstance = {
                request: function (config) {
                    var $route = $injector.get('$route');
                    config.headers['X-MyApp-CustomHeader'] = $route.current.params.CustomParameter; 
                    return config || $q.when(config);
                }
            };
            return interceptorInstance;
        }];

    $httpProvider.interceptors.push(requestInterceptor);
}]);

what is $injector?

  • You must read the docs
  • And see this great tutorial

$injector is used to retrieve object instances as defined by provider , instantiate types, invoke methods, and load modules.

Internally, angular.js would use $injector to invoke your methods ( config / run blocks ) with all the dependencies injected. This happens automatically so you rarely need to worry about it. In cases where $injector fails to resolve your dependencies you can do it manually.



来源:https://stackoverflow.com/questions/21229177/inject-route-into-a-http-interceptor

工具导航Map

JSON相关