簡體   English   中英

Angular:攔截ajax請求,檢查互聯網連接,不發送請求

[英]Angular: intercept ajax request, check internet connection and not send request

我在Angular(帶有Ionic)應用程序中有一段代碼:

my_app.factory('connectivityInterceptorService', ['$q', '$rootScope', function ($q, $rootScope) {
    var connectivityInterceptorServiceFactory = {};
    var _request = function (config) {
        if(navigator.connection) {
            if(navigator.connection.type == Connection.NONE) {

            }
        }
        return config;
    };

    connectivityInterceptorServiceFactory.request = _request;
    return connectivityInterceptorServiceFactory;
}])

navigator.connection可以返回連接的“type”(使用cordova插件)(wifi,3G,none等)。 這段代碼工作正常,我可以檢測設備是否有連接。 問題是:我想在if語句中“取消”請求。 但我無法弄清楚是否有可能。

據我所知,如果您使用舊的$ http來發出請求,請求的'timeout'屬性可以附加到promise並在解析promise時解析:

摘自導游:(鏈接如下)

// The timeout property of the http request takes a deferred value        
// that will abort the underying AJAX request if / when the deferred                  
// value is resolved.

所以你可以做的是讓你的連接函數返回$ http超時的承諾,並將其解析為某個值,以便在沒有連接時激活超時。

鏈接指南: http//www.bennadel.com/blog/2616-aborting-ajax-requests-using-http-and-angularjs.htm

希望能幫助到你 !

暫無
暫無

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

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