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

I have code like this in an Angular app (with 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 can return the "type" (using the cordova plugin) of the connection (wifi, 3G, none, etc.). This code works fine, I can tell if the device has a connection or not. The thing is, I want, inside this if statement, to cancel the request. But I cannot figure out if this is possible.

+3


source to share


1 answer


As far as I know, if you are using good old $ http for the request, the "timeout" property of the request can be bound to the promise and decide when the promise is resolved:

Taken from the manual: (link below)

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

      



So what you can do is let your connection function return a promise to the $ http timeout and allow it to be a specific value to trigger the timeout if there is no connection.

Manual link: http://www.bennadel.com/blog/2616-aborting-ajax-requests-using-http-and-angularjs.htm

Hope it helps!

+2


source







All Articles