Kuba T
Kuba T

Reputation: 3083

Shared AngularJS $http interceptors

I am wondering if Angular.js $http interceptors are shared thoughout the whole application.
Let's assume I have a myDependentApp module, shared between many apps. That module has some interceptor configured to control the $http requests/responses. I include that module by declaring it in application bootstrap:

angular.module('myApp', ['myDependentApp']);

And I have application template:

<html ng-app="myApp">

Are myDependentApp's interceptors going to be active in myApp?

Thanks for help.

Upvotes: 3

Views: 2393

Answers (3)

mengstrom
mengstrom

Reputation: 233

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.

Upvotes: 1

Jochen van Wylick
Jochen van Wylick

Reputation: 5401

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/

Upvotes: 6

przno
przno

Reputation: 3504

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

Upvotes: 0

Related Questions