Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Interceptor TypeError: Cannot read property 'headers' of undefined

I am Getting this Error for unknown reasons while trying to implement a AJAX Spinner loading code.

I don't understand where the header should be defined. I did console.log(config) but I can see headers: accept: text/html value there.

Below is my Code:

/**
* Spinner Service
*/

//Spinner Constants
diary.constant('START_REQUEST','START_REQUEST');
diary.constant('END_REQUEST','END_REQUEST');

//Register the interceptor service
diary.factory('ajaxInterceptor', ['$injector','START_REQUEST', 'END_REQUEST', function ($injector, START_REQUEST, END_REQUEST) {
    var $http,
    $rootScope,
    myAjaxInterceptor = {
        request: function (config) {
            $http = $http || $injector.get('$http');
            if ($http.pendingRequests.length < 1) {
                console.log(config);
                $rootScope = $rootScope || $injector.get('$rootScope');
                $rootScope.$broadcast(START_REQUEST);
            }
        }
    };

    return myAjaxInterceptor;
}]);

diary.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('ajaxInterceptor');
}]);
like image 336
ChanX Avatar asked Mar 29 '15 09:03

ChanX


Video Answer


1 Answers

I think I have the solution.

I've had the same problem under an AngularJS project where an interceptor is exactly defined the same as yours (https://docs.angularjs.org/api/ng/service/$http#interceptors)

To shorten, an interceptor catch the config and have to return it. And you forgot to.

So that would be:

request: function (config) {
    $http = $http || $injector.get('$http');
    if ($http.pendingRequests.length < 1) {
        $rootScope = $rootScope || $injector.get('$rootScope');
        $rootScope.$broadcast(START_REQUEST);
    }
    return config;
}
like image 78
Quidam Avatar answered Oct 20 '22 17:10

Quidam