Network Connection Check

Hi,

How can i detect network connection in each controller or in every request ?

following code checks network on app start… but not on every request…

if(window.Connection) {
  if(navigator.connection.type == Connection.NONE) {
      alert('There is no internet connection available');
  }else{
      alert(navigator.connection.type);
  }
}
else{
      alert('Cannot find Window.Connection');
}

I want to check it on each controller or even on each request…

Any help will be appreciated…

Thank you.

Create a Network Connection service.

Good Luck,

RGecy

Hi @BGecko ,

I have tried the tutorial but no luck… first of all i don’t understand where to i call

ConnectivityMonitor.isOnline()

Secondly i have tried it my way… so it is showing me online once app loads but after that nothing is working… in both chrome browser and on genymotion…

following is my code :

.controller('mmDashboardController',['ConnectivityMonitor','$scope', '$state', '$rootScope', '$cordovaNetwork', function (ConnectivityMonitor,$scope, $state, $rootScope, $cordovaNetwork) {
  ConnectivityMonitor.isOnline();
  ConnectivityMonitor.isOffline();
  ConnectivityMonitor.startWatching();
  $scope.test = function () {
    $state.go('mainMaster.Test', {}, {reload: true});
  }
}])

.factory('ConnectivityMonitor', function($rootScope, $cordovaNetwork){
 
  return {
    isOnline: function(){
      if(window.cordova){
        return $cordovaNetwork.isOnline();    
      } else {
        console.log("navigator.onLine");
        return navigator.onLine;
      }
    },
    isOffline: function(){
      if(window.cordova){
        return !$cordovaNetwork.isOnline();    
      } else {
        console.log("!navigator.onLine");
        return !navigator.onLine;
      }
    },
    startWatching: function(){
      if(window.cordova){
        console.log("i am in startWatching if");
        $rootScope.$on('$cordovaNetwork:online', function(event, networkState){
            console.log("went online");
          });
 
          $rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
            console.log("went offline");
          });
      }
      else {
        console.log("i am in startWatching else");
        window.addEventListener("online", function(e) {
          console.log("went online");
        }, false);    

        window.addEventListener("offline", function(e) {
          console.log("went offline");
        }, false);  
      }       
    }
  }
})

Note : I am using window.cordova instead of ionic.Platform.isWebView() and this is not problem…

Thank you.