每当执行http请求时,我都会使用以下内容显示加载屏幕,但是有时如果出现错误,它将保持加载状态(由于该应用无法使用,因此会在后台显示)。而不是在每个错误检查器上都隐藏它,我想知道是否可以在5秒后调用超时?
.config(function($httpProvider) {
$httpProvider.defaults.timeout = 5000;
$httpProvider.interceptors.push(function($rootScope) {
return {
request: function(config) {
$rootScope.$broadcast('loading:show')
return config
},
response: function(response) {
$rootScope.$broadcast('loading:hide')
return response
}
}
})
})
遵循Jess的回答,现在看起来像这样:
.config(function($httpProvider) {
$httpProvider.defaults.timeout = 5000;
$httpProvider.interceptors.push(function($rootScope) {
return {
request: function(config) {
$rootScope.$broadcast('loading:show')
return config
},
response: function(response) {
$rootScope.$broadcast('loading:hide')
return response
},
responseError: function(response) {
$rootScope.$broadcast('loading:hide')
return response
},
requestError: function(response) {
$rootScope.$broadcast('loading:hide')
return response
}
}
})
})
但是,我似乎无法在中发出警报requestError
来通知用户。
问题我如何实施警报以通知用户已发生的错误?
尝试添加responseError
,requestError
像这样:
responseError: function(responseError) {
$rootScope.$broadcast('loading:hide')
return responseError
并再次使用requestErro
r进行此操作,这是从有角度的http拦截器文档中获得的
requestError
:当先前的拦截器抛出错误或被拒绝解决时,拦截器将被调用。
responseError
:当先前的拦截器抛出错误或被拒绝解决时,拦截器将被调用。
编辑以回答评论:
因此,如果您想发出警报,请responseError
添加一个$rootScope.$broadcast('response:error')
在responseError函数中
然后在控制器中您要发出警报,只需执行
$scope.$on('response:error', function(){throw the error here});
您也可以为 requestError
之所以起作用是因为$broadcast
-将事件向下调度到所有子范围
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句