Shared AngularJS $http interceptors

一个人想着一个人 提交于 2019-12-05 21:03:35

The answer is yes, I tried it here:

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');
}]);

And I saw that the request was being intercepted. Here's the fiddle: http://jsfiddle.net/6dbgo6pt/1/

The answer is Yes.

Directly from the 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 is one such service createad using the provider recipe.

So this means that every module in your app will be served the very same $http service and those modules adding interceptors will be shared with the modules since again, the $http service is a singleton like any other angular- or custom built service using .service, .factory or .provider.

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

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