AngularJS Interceptor TypeError: unable to read property headers undefined

I get this error for unknown reasons while trying to implement the AJAX Spinner download code.

I do not understand where the title should be indicated. I did console.log(config) , but I see there the value of headers: accept: text/html .

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'); }]); 
+6
source share
2 answers

I think I have a solution.

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

To shorten, the interceptor will catch the configuration and must return it. And you forgot.

So this will 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; } 
+12
source

Here you have a complete example on how to implement a spinner using hooks (wrapping $ rootScope in a service for better code readability).

http://lemoncode.net/2013/07/31/angularjs-found-great-solution-to-display-ajax-spinner-loading-widget/

As you pointed out, this is deprecated (I need to update the message), the current structure I'm using (simplified internal code). I think that it would be best to start with a plunker, maybe this has nothing to do with how to implement the tou (let me look for the plunkr seed)

 myapp.factory('httpInterceptor', ['$q', '$injector', function ($q, $injector) { return { 'request': function(config) { // request your $rootscope messaging should be here? return config; }, 'requestError': function(rejection) { // request error your $rootscope messagin should be here? return $q.reject(rejection); }, 'response': function(response) { // response your $rootscope messagin should be here? return response; }, 'responseError': function(rejection) { // response error your $rootscope messagin should be here? return $q.reject(rejection); } }; } ]); 
0
source

Source: https://habr.com/ru/post/984381/


All Articles