AngularJS有种机制叫做拦截器(interceptor),它是$http扩展点,类似ASP.NET MVC的过滤器filter机制,对每个$http请求的发送和接收过程进行过滤。
$httpProvider
中有一个 interceptors
数组,定义一个工厂服务,并添加到该数组中。
module.config(['$httpProvider', function($httpProvider) { $httpProvider.interceptors.push('myInterceptor'); }]);
定义factory,返回一个对象,有属性request,requestError,response,responseError属性,对每个请求及其进行统一处理,对每次请求都添加上身份认证信息,构造附加的请求地址前缀等,对响应如果有错误或异常,进行统一处理,或弹出对话框。
module.factory('myInterceptor',
['$q', '$log', '$injector', 'loginContext', 'eventAggregator', 'maintainUtil',
function ($q, $log, $injector, loginContext, eventAggregator, maintainUtil) {
'use strict'; var apiToken = loginContext.apiToken;
var tokenType = loginContext.tokenType;
var webApiHostUrl = loginContext.apiHost + "/api/v1"; return {
//token save to services for further usage
tokenType: tokenType,
apiToken: apiToken,
webApiHostUrl: webApiHostUrl, // On request success
request: function (config) {
if (config.isWebApiRequest && !config.isPlugin) {
config.url = (config.mkApiUrl || webApiHostUrl) + config.url;
config.headers = config.headers || {};
config.headers.Authorization = tokenType + ' ' + (config.mkToken || apiToken);
var specificOfficeId = Mres.specificOfficeUtil.getOfficeId();
if (specificOfficeId) {
config.headers["specific-office-id"] = specificOfficeId;
}
} else if (config.handleApiRequest) {
config = config.handleApiRequest(config);
}
return config;
},
// On request failure
requestError: function (rejection) {
$log.error(rejection); // Contains the data about the error on the request.
// Return the promise rejection.
return $q.reject(rejection);
},
// On response failture
responseError: function (response) {
$log.error(response); // Contains the data about the error.
if (response.status === 401) {
//window.location = '/logoff';
Mres.logOff();
} else if (response.data) {
if (response.data.name == 'MenantInactiveException') { aresMaintainUtil.goToMenantInactivePage();
}
eventAggregator.publish(eventAggregator.events.ApiErrorHappened, response, 'myInterceptor');
} else if (response.status === 0) {
var isSaasApi = true;
if (response.config && response.config.url.indexOf('//marketcenter') > -1) {
isSaasApi = false;
}
if (isSaasApi) {
aresMaintainUtil.ensureInMaintainMode().then(function (isInMaintainMode) {
if (isInMaintainMode) {
mresMaintainUtil.goToMaintainPage();
}
});
}
}
// Return the promise rejection.
return $q.reject(response);
}
};
}])
适用于对每次请求和响应附加统一功能或数据。