【问题标题】:Angular: intercept ajax request, check internet connection and not send requestAngular:拦截ajax请求,检查互联网连接而不发送请求
【发布时间】:2015-07-24 11:06:35
【问题描述】:

我在 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 可以返回连接的“类型”(使用 cordova 插件)(wifi、3G、none 等)。 此代码完美运行,我可以检测设备是否连接。问题是:我想在这个 if 语句中“取消”请求。但我不知道是否有可能。

【问题讨论】:

    标签: javascript angularjs cordova ionic-framework ionic


    【解决方案1】:

    据我所知,如果您使用旧的 $http 发出请求,则可以将请求的“超时”属性附加到承诺并在承诺解决时解决:

    取自指南:(下面的链接)

    // 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

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-18
      • 1970-01-01
      • 2013-05-24
      • 1970-01-01
      • 1970-01-01
      • 2019-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多