如何设置全局 AJAX 处理程序,仅当我尚未为特定 AJAX 调用定义错误处理程序时才会调用该处理程序?
如果发生错误,我的一些ajax调用确实需要执行一些逻辑(例如重新启用按钮),但对于某些AJAX,我只需要在发生错误时显示错误消息。
例如,此代码没有为 AJAX 调用定义任何错误处理程序,因此我想应用于此调用全局错误处理程序,我将在其中仅显示错误消息:
user.$delete().then(function () {
// on success
});
但是这个 AJAX 调用已经定义了错误处理程序,并且我不想对其应用全局处理程序:
$scope.deleteButtonEnabled = false;
user.$delete().then(function () {
// on success
}, function(err) {
// Do some stuff and then show error message
$scope.deleteButtonEnabled = true;
alert('Error' + JSON.stringify(err))
});
最佳答案
您可以使用interceptors以及 http 调用中的一些配置。
定义拦截器:-
angular.service('HttpInterceptor', function($q){
var service = {
response:function(response) { //Only if you need
//If you have to handle response data based errors you could do this here
return $q.when(response);
},
responseError: function(response){
if(!response.config.suppressGlobal){ //Handle error only if the global error handling is not suppressed
//Handle Error based
alert('Error' + response.status);
}
return $q.reject(response);
}
};
}).config(['$httpProvider', function($httpProvider){
$httpProvider.interceptors.push('HttpInterceptor'); //Push the interceptor here
}]);
在您的服务示例中,当您进行 http 或资源调用时,让该方法采用可选的 bool 参数来抑制全局错误处理程序,将其与 http 的 config
字典参数一起传递调用:-
app.service('userService', function(){
this.getData = function(suppressGlobal){ //Take a flag to suppress globals
return http.get('...', {suppressGlobal:suppressGlobal}).. //Pass the flag in the config
};
this.delete = function(suppressGlobal){ //Take a flag to suppress globals
return http.delete('...', {suppressGlobal:suppressGlobal}).. //Pass the flag in the config
}
this.add = function(suppressGlobal){//Take a flag to suppress globals
return http.post('..', data, {suppressGlobal:suppressGlobal}).. //Pass the flag in the config
}
});
当您调用电话时:-
// Code that needs global error handling
user.delete().then(function () { //just call your service method as is
// on success
});
在其他地方:-
// Code that needs to suppress global error handling
user.delete(true).then(function () { //Pass true as argument to the delete which will supress global error handling.
// on success
}, function(err) {
// Do some stuff and then show error message
$scope.deleteButtonEnabled = true;
alert('Error' + JSON.stringify(err))
});
关于javascript - AngularJS。添加全局 AJAX 错误处理程序(如果尚未定义),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26087807/