一、定义一个Interceptor
responseError: 响应失败(404,401等)
response: 响应成功(在这可以处理自定义权限、登录状态判断等过滤)
request:请求发生成功
requestError: 请求失败
参考代码:
/**
* 自定义过滤器
* @type {module}
*/
var ngFilters = angular.module('ngFilters', []);
/**
* http 权限,响应状态等过滤
*/
ngFilters.factory('httpInterceptor', [ '$q', '$injector',function($q, $injector) {
var httpInterceptor = {
'responseError': function (response) {
console.log(response, "responseError");
if(response.status == 401) { // 401 Unauthorized 当前请求需要用户验证
var rootScope = $injector.get('$rootScope');
//var state = $injector.get('$rootScope').$state.current.name;
//rootScope.stateBeforLogin = state;
var state = $injector.get('$state');
state.go("unauthorized");
} else if(response.status === 404) { // 404 Not Found
console.log("404!");
var state = $injector.get('$state');
state.go("error404");
return $q.reject(response);
} else if(response.status === 408) { // 408 Request Timeout
console.log("408!");
var state = $injector.get('$state');
state.go("unauthorized");
return $q.reject(response);
}
return $q.reject(response);
}/*,
'response': function (response) { // response success
console.log(response, "response");
// TODO 后台响应状态过滤 response.data.code 或者在统一的ajax、http做拦截
return response;
},
'request': function (config) { // request success
//console.log(config, "request");
return config;
},
'requestError': function (config) {
//console.log(config, "requestError");
return $q.reject(config);
}*/
}
return httpInterceptor;
}
]);
二、app启动时,在config中使用 $httpProvider添加注册上面创建的httpInterceptor拦截器。这样在后续程序中使用http与后台数据交互时就会进行拦截。
var ngApp = angular.module('ngApp', ['ui.router','ngFilters']);
ngApp.config(function ($stateProvider, $urlRouterProvider, $httpProvider) {
// 注册httpInterceptor
$httpProvider.interceptors.push('httpInterceptor');
// 路由
$stateProvider
.state('main', { // 首页
url: '/main',
templateUrl: 'tpls/main.html'/*,
controller: 'MainCtrl'*/
});
});