inject $route into a http interceptor

限于喜欢 提交于 2019-12-03 15:55:59
Ilan Frumer

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?

$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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!