In this post I will discuss how to use network connection in ionic . Whenever you want to make an web service app you need to first check your internet connection . So just follow my step .
First of all open command prompt and got to your project folder directory . We need to install a plugin for checking internet connection . So just run this command given in the bellow :-
cordova plugin add org.apache.cordova.network-information
Now open your app.js file of your project and edit this using the bellow code .
//for network .factory('ConnectivityMonitor', function($rootScope, $cordovaNetwork){ return { isOnline: function(){ if(ionic.Platform.isWebView()){ return $cordovaNetwork.isOnline(); } else { return navigator.onLine; } }, isOffline: function(){ if(ionic.Platform.isWebView()){ return !$cordovaNetwork.isOnline(); } else { return !navigator.onLine; } }, startWatching: function(){ if(ionic.Platform.isWebView()){ $rootScope.$on('$cordovaNetwork:online', function(event, networkState){ console.log("went online"); }); $rootScope.$on('$cordovaNetwork:offline', function(event, networkState){ console.log("went offline"); }); } else { window.addEventListener("online", function(e) { console.log("went online"); }, false); window.addEventListener("offline", function(e) { console.log("went offline"); }, false); } } } })
Now we will do everything using this object ConnectivityMonitor . This means we first check the connection using it for every sever request . So whenever you want to use this just put it into the function parameter and check a condition using isOnline() method . Just as bellow :
angular.module('starter').controller('loginController',function($scope,ConnectivityMonitor){ $scope.login = function(){ if(ConnectivityMonitor.isOnline()){ //here your code for server side data access } else{ //show network error or something. } } }
If you want to get any further details , then just put a comment .