Javascript 如何使用Angular JS拦截每个Ajax请求
我需要截获每个Ajax请求,以验证服务器是否响应了Javascript 如何使用Angular JS拦截每个Ajax请求,javascript,jquery,ajax,angularjs,Javascript,Jquery,Ajax,Angularjs,我需要截获每个Ajax请求,以验证服务器是否响应了401 Unauthorized,因为会话已过期并重定向到登录页面,因此用户不会认为应用程序停止工作。我可以使用JQuery通过以下方式实现这一点: $( document ).ajaxComplete(function( event, xhr, settings ) { if(xhr.errorCode == 401 || xhr.responseText === "unauthorized") { location.href =
401 Unauthorized
,因为会话已过期并重定向到登录页面,因此用户不会认为应用程序停止工作。我可以使用JQuery通过以下方式实现这一点:
$( document ).ajaxComplete(function( event, xhr, settings ) {
if(xhr.errorCode == 401 || xhr.responseText === "unauthorized") {
location.href = "/Login";
}
});
如何使用Angular JS实现这一点?创建一个用于进行所有调用的函数,您只需在一个位置而不是多个位置处理错误
function makeCall(obj, cb) {
$http({
method: obj.method,
url: obj.url,
data: obj.data || {}
}, function(res) {
// non error statuses get handled here
}, function(res) {
// error statuses get handled here
})
}
使用
httpInterceptor
。一段时间以前也有过类似的问题。然后,您应该对hanndler感兴趣,并在那里添加您的特定逻辑。您可以在application config()上设置$interceptor
:(你有被否决的风险…你应该解释一下你在Angular中查找到了什么,并显示了失败的选项..看一看。你可以在配置过程中这样做。这只针对一个请求,他需要为每个请求执行此操作。请参阅编辑版本。对所有调用使用此函数-在那里编写错误处理块。这仍然是一个糟糕的结果。)lution,因为$http服务已经包含用于处理该问题的httpInterceptros。
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(['$location', '$q', function($location, $q) {
return {
'request': function(request) {
return request;
},
'responseError': function(response) {
if (response.status === 401) {
// do stuff
}
// otherwise, default behaviour
return $q.reject(response);
}
};
}]);
}])