共享 AngularJS $http 拦截器

Shared AngularJS $http interceptors

我想知道 Angular.js $http 拦截器是否在整个应用程序中共享。
假设我有一个 myDependentApp 模块,在许多应用程序之间共享。该模块配置了一些拦截器来控制 $http requests/responses。我通过在应用程序 bootstrap:

中声明它来包含该模块
angular.module('myApp', ['myDependentApp']);

我有申请模板:

<html ng-app="myApp">

myDependentApp 的拦截器是否会在 myApp 中启用?

感谢您的帮助。

$http Interceptors:

For purposes of global error handling, authentication, or any kind of synchronous or asynchronous pre-processing of request or postprocessing of responses, it is desirable to be able to intercept requests before they are handed to the server and responses before they are handed over to the application code that initiated these requests. The interceptors leverage the promise APIs to fulfill this need for both synchronous and asynchronous pre-processing.

The interceptors are service factories that are registered with the $httpProvider by adding them to the $httpProvider.interceptors array. The factory is called and injected with dependencies (if specified) and returns the interceptor.

$httpProvider:

Use $httpProvider to change the default behavior of the $http service.

答案是肯定的,我在这里试过了:

var dependentApp = angular.module('dependency',[]).config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push(function ($q) {
        return {
            'request': function (config) {
                console.log('request intercept');
            },

                'response': function (response) {
                console.log('response intercept');
            }
        };
    });
}]);

var app = angular.module('myapp', ['dependency']);
app.controller('mycontroller', ['$scope', '$http', function ($scope, $http) {
    $http.get('http://www.google.com');
}]);

而且我看到请求被拦截了。这是 fiddle:http://jsfiddle.net/6dbgo6pt/1/

答案是肯定的。

直接来自 docs

Angular services are:

Lazily instantiated – Angular only instantiates a service when an application component depends on it.

Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.

$http 是使用 provider recipe.

创建的此类服务之一

所以这意味着您应用程序中的每个模块都将提供完全相同的 $http 服务,并且那些添加拦截器的模块将与模块共享,因为 $http 服务是单例与使用 .service.factory.provider.

的任何其他 angular 或自定义构建服务一样