Show modal when device Network Status is offline


#1

Hello Fellow Ionions,

I am new to angular and ionic and I have been enjoying myself learning this awesome framework and angular. I am currently building an app which relies heavily on $http (ajax) request.

I wanted to find out, what is the best practice to show a modal when the device goes offline. Built in Cordova plugin, ng-cordova or does ionic has something?

My questions are:

  • Is there a global event listener that I can use or register, that will fire an event and launch the modal whenever the device goes offline? If so, how? Should it be a service or within the main app controller?
  • When the device is back online, I want to be able to hide the modal. Can this be done?

Any help here would be appreciated.

Thanks!

Kind Regards,
Syed


#2

Please take a look at the cordova events, they fire “online” and “offline” corrsepondingly. The big challenge is in supporting the same functionality for desktop browsers though…

https://cordova.apache.org/docs/en/3.0.0/cordova_events_events.md.html#online
https://cordova.apache.org/docs/en/3.0.0/cordova_events_events.md.html#offline


#3

For browsers, you can use navigator events , but they will not work properly on anything else other than Internet Explorer in my experience. So the best way to do it is check the connection with a 1x1 pixel image hosted somewhere, and using onload and onerror to see where it was loaded or not. Also you must use custom javascript random so that the file will not be cacheable. I do it like this:

    $rootScope.refreshConnectionState = function checkConnectionWithImage() {
        var connected = true;
        var imageid = document.getElementById("somerandomID");
        if (!(imageid))
        {
        var img = document.createElement('img');
        img.id="somerandomID";
        }
        img.src = "http://upload.wikimedia.org/wikipedia/commons/c/ca/1x1.png?id=" + Math.random();
        img.onerror = function () {
            if ($rootScope.online == true)
            $rootScope.$broadcast('becameOffline');
            connected = false;
            $rootScope.online = false;
        }
        img.onload = function () {
            if ($rootScope.online == false)
            $rootScope.$broadcast('becameOnline');
            connected = true;
            $rootScope.online = true;
        }
    }

But make sure to use the refreshConnection() in your HTML templates, as ng-init , or ng-click, depending on how you need it.From there you can $rootScope.$on(‘becomeOnline’,showmodal());

For the modal part, here’s an example for how to use it.
http://codepen.io/ionic/pen/gblny ,it’s pretty simple an straightforward . Here is more documentation
http://ionicframework.com/docs/api/service/$ionicModal/

I hope it helped you my friend,with alll this md5hash-majoogaly like a someboooooooooody