离子http请求加载超时

时间:2015-07-17 15:03:20

标签: angularjs timeout ionic-framework

我正在使用以下内容在我执行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中发出警报来通知用户。

问题 如何实现警报以通知用户已发生的错误?

1 个答案:

答案 0 :(得分:2)

尝试添加responseErrorrequestError,如下所示:

 responseError: function(responseError) {
                $rootScope.$broadcast('loading:hide')
                return responseError

并使用requestErro r再次执行此操作, 这是来自角度的http拦截器文档

requestError:当前一个拦截器抛出错误或通过拒绝解决时,会调用拦截器。

responseError:当前一个拦截器抛出错误或通过拒绝解决时,会调用拦截器。

编辑以回答评论:

因此,如果您想在responseError上发出提醒,而不是添加$rootScope.$broadcast('response:error')

函数中的

然后在控制器中你想要发出警报只需做一个

$scope.$on('response:error', function(){throw the error here});

您也可以对requestError

执行相同的操作

这是有效的,因为$broadcast - 将事件向下调度到所有子范围