簡體   English   中英

ionic http請求加載超時

[英]ionic http request loading timeout

每當執行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放置警報以通知用戶。

問題如何實施警報以通知用戶已發生的錯誤?

嘗試添加responseErrorrequestError ,如下所示:

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

然后使用requestErro r再次執行此操作,這是從有角度的http攔截器文檔中獲得的

requestError :當先前的攔截器拋出錯誤或被拒絕解決時,攔截器將被調用。

responseError :前一個攔截器拋出錯誤或被拒絕解決時,攔截器將被調用。

編輯以回答評論:

因此,如果您想對responseError發出警報, responseError不是添加$rootScope.$broadcast('response:error')

在responseError函數中

然后在控制器中您要發出警報,只需執行

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

您也可以對requestError做同樣的事情

之所以有效,是因為$broadcast將事件向下調度到所有子范圍

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM