我的代码发出了许多AngularJS $http请求。通常是3-4同时进行.
是否有什么方法可以拦截http消息,以便在internet连接丢失且正在进行多个请求时,只会弹出one警报?我见过其他站点也会这样做,但是如果这个操作需要很多http调用,我似乎会看到不止一个错误弹出。
如果可能的话,我只想在代码中的一个地方这样做。
发布于 2015-02-07 10:01:05
在角的配置阶段,您需要在responseInterceptors内部添加$httpProvider。这个interceptor在角$httpProvider处理响应后被调用。
码
module.config(['$httpProvider', function($httpProvider) {
var interceptor = ['$rootScope', '$q', '$location', function(scope, $q, $location) {
function success(response) {
return response;
}
function error(response) {
var status = response.status;
if (status == 500) {
alert("Internal Server Error")
return;
}
if (status == 404) {
alert("Page not found")
return;
}
// otherwise
return $q.reject(responseInterceptors);
}
return function(promise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);
}]);当任何请求失败时,上述代码将为您提供更好的错误处理控制。
有关更多细节,请参见this anwser。
更新
为了只显示一次警报,我们可以创建一个服务,如果发生错误,那么这将处理设置错误变量。
服务
module.service('errorService',function(){
//getter
this.getErrorFlag = function(){
return this.isError;
}
//setter
this.setErrorFlag = function(val){
this.isError = val;
}
});阻断器
module.config(['$httpProvider', function($httpProvider) {
var interceptor = ['$rootScope', '$q', '$location','errorService', function(scope, $q, $location,errorService) {
function success(response) {
return response;
}
function error(response) {
//setting error variable
errorService.setErrorFlag(true)
return $q.reject(responseInterceptors);
}
return function(promise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);
}]);在控制器内部,将所有$http调用承诺放在$q.all中,当承诺被解析时,检查errorService的isError标志。如果错误至少发生一次,则IsError标志将为真&通过使用它,您只能显示错误一次。
控制器
module.controller('appCtrl',['$scope','$q','errorService',function($scope,$q,errorService){
var ajax1 = $http.get('url').then(function(){
},
function(){
});
var ajax2 = $http.get('url').then(function(){
},
function(){
});
var ajax3 = $http.get('url').then(function(){
},
function(){
});
errorService.setErrorFlag(false);
$q.all(ajax1, ajax2, ajax3).then(function(data){
//check for isError flag from service
if(errorService.getErrorFlag())
alert('Error occurred while processing request.'); //this will show only once
else
alert('No error occurred while processing request.')
});
}]);希望这能帮到你。谢谢。
发布于 2015-02-07 20:42:57
如果不想使用拦截器,只需处理error调用的$http回调:
$scope.httpError = null;
$scope.processHttpError = function() {
// If you don't already have got an http error
if (!$scope.httpError) {
$scope.httpError = "Cannot load stuff";
}
};
$http.get('/someUrl')
.success(function(data, status, headers, config) { ... })
.error($scope.processHttpError);https://stackoverflow.com/questions/28379923
复制相似问题