Claudius Ibn Claudius Ibn - 28 days ago 9
HTTP Question

AngularJS - Put $http interceptor in separate file

How can I put my interceptor in a separate file and push it in the $httpProvider within the configuration block.

Here's my configuration block at the moment:

(function() {
'use strict';

angular
.module('app')
.config(config);

config.$inject = ['$httpProvider'];

function config($httpProvider) {
$httpProvider.defaults.withCredentials = true;
$httpProvider.defaults.useXDomain = true;
$httpProvider.interceptors.push(['$injector', '$q', function($injector, $q) {
return {
responseError: function(response) {
var toastr = $injector.get('toastr');
var lodash = $injector.get('lodash');
toastr.error(lodash.get(response, 'data.message', 'Alguma coisa deu errado.'));
if (response.status !== 401) {
return $q.reject(response);
}

var userService = $injector.get('userService');
if (userService.isLogged()) {
userService.logout();
}

var $state = $injector.get('$state');
$state.go('login');
return $q.reject(response);
}
};
}]);
}
})();

Answer

Create a factory using your code inside return {.....} and push that factory to intercepters collection.

angular .module('app') .config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('yourInterceptorFactoryName'); }]);