3
3
3Doleg2015-12-17 23:39:22
JavaScript
3Doleg, 2015-12-17 23:39:22

Why do interceptors in Angular respond to every request?

I have 2 modules and each module has services for working with $http. I write 2 interceptors in the config of these 2 modules, respectively, implement the 'request' method there, and then push all this to $httpProvider in the config. Why, when I make a request outside of these modules, they still respond to requests, and also load headers, footers, etc.?
Module 1:

var module1 = angular.module('Module1', []);

module1.config(['$httpProvider', function($httpProvider){

    function a1($q) {
        return {
            'request': function (config) {
                    console.log('request 1');
                    return config;  
            }
        };
    }
    
    $httpProvider.interceptors.push(a1);

}]);

Module 2:
var module2 = angular.module('Module2', []);

module2.config(['$httpProvider', function($httpProvider){

    function a1($q) {
        return {
            'request': function (config) {
                    console.log('request 2');
                    return config;  
            }
        };
    }
    
    $httpProvider.interceptors.push(a1);

}]);

And I connect them to the main module.
Result:
9f3cb4936249487a8ec58b3f154341a4.png
And I need my own processing in each module, I used Promises before, I wonder if it can be done with this method ...
And for backfilling: if I still process with promises, and I do the registration using Interceptors, will one overlap the other?
Thanks a lot!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nicholas, 2015-12-18
@healqq

You are using the interceptor incorrectly. It is needed not to process the response, but to convert the response received from the server into the desired form, or for some other actions that need to be performed during the direct processing of the response.
To process the actual response, you need to use the Promises API:

// $http и $resource возвращают Promise
$http.get('/my/cool/url')
.then(function(data) {
    // здесь обрабатываем корректный результат запроса
},
function(error) {
    // здесь некорректный
});

Check out the $resource service , it's a small wrapper around $http, quite handy, especially when working with a RESTfull API.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question