Reputation: 372
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');
}]);
Upvotes: 7
Views: 10666
Reputation: 1728
Here you have a full sample about how to implement a spinner using interceptors (wrapping the $rootScope in a service for better code readibility).
As you pointed out, this is deprecated (I have to update the post), the current structure I'm using (simplified inner code). I think the best could be to start from a plunker, maybe it has nothing to do with the way tou are implementing (let me search for a seed plunkr)
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);
}
};
}
]);
Upvotes: 1
Reputation: 209
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;
}
Upvotes: 12