在我的 Angular 应用程序中,我想向外部 API 的所有调用添加信息。
为此,我使用从 app.config 中调用的拦截器。
app.config(['$httpProvider', ... , function($httpProvider, ...){
$httpProvider.interceptors.push('globalInterceptorService');
$httpProvider.interceptors.push('authInterceptorService');
}]);
当我只使用一个拦截器时,它工作得很好。但是当我使用其中两个(如上例所示)时,其中一个的操作会被另一个覆盖。
知道如何处理多个拦截器吗?也许建议只拥有 1 个?非常感谢任何帮助。
拦截器1:
function globalInterceptorService ($q, localStorageService) {
var service = {};
var _request = function (config) {
config.headers = config.headers || {};
var AreaId = localStorageService.get('AreaId');
if (AreaId) {
config.headers.AreaId = 'AreaId ' + AreaId;
}
return config;
};
service.request = _request;
return service;
}
拦截器2:
function authInterceptorService ($q, $location, localStorageService) {
var service = {};
var _request = function (config) {
config.headers = config.headers || {};
var authData = localStorageService.get('authorizationData');
if (authData) {
config.headers.Authorization = 'Bearer ' + authData.token;
}
return config;
};
service.request = _request;
return service;
}
最佳答案
我认为你应该推送函数,而不是它的字符串名称。
function globalInterceptorService($q, localStorageService){...}
$httpProvider.interceptors.push(globalInterceptorService);
示例:http://jsfiddle.net/aartek/tbhobfbu
或者
function globalInterceptorService($q, localStorageService){...}
$provide.factory('globalInterceptorService',globalInterceptorService)
$httpProvider.interceptors.push('globalInterceptorService');
示例:http://jsfiddle.net/aartek/tbhobfbu/2/
documentation 中有很好的描述。
关于angularjs - app.config 中的 Angular 多个拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30868590/