How to detect “no internet connection” using ANGULAR JS

Today i need to show some message when internet connection lost. So I define this interceptor in httpProvider in my app.js file, so its return an error when a call does not happen successfully due to internet connection lost. This Interceptor return status= "-1" when ajax call is failed. So i set a variable online= true here and in my html i display a message if online=true. See below my html code as well


angular.module('YourAppName', []).config([
  '$httpProvider',
  function($httpProvider){
    $httpProvider.interceptors.push([
      '$q','$rootScope',
      function($q,$rootScope) {
        return {
            responseError: function(res){
                //Angular returns "success" by default, but we will call "error" if data were not obtained.
                if(res.data == null && res.status === -1 && res.statusText === ""){
      $rootScope.online = true;
                    return $q.reject(res) //callback error()
                }      
                return res //return default success()
            }
        };
      }
    ]);
  }
]);


Now i need to show some message when $rootScope.online = true;
Below i check that online variable is true then show a message "Your have lost your internet connection. Check your internet connection and reload your page again." other wise not.


<!--Below message is showing when internet connection is lost. --> 
<div class="alert alert-error" ng-if="online"><i class="btn-icon-only icon-warning-sign"></i>
 Your have lost your internet connection. Check your internet connection and reload your page again.<button ng-click="reloadRoute()"><i class="icon-refresh"></i> Reload</button>
</div>

If you see my above html there i also add a reload button to reload the page to do this i create a function and i call this on click of reload button Below is my function :

// This function Is use to reload the active page.
$rootScope.reloadRoute = function() {
   $route.reload();
}

Now in the last step you need to hide the above message automatically when internet connection is coming again to do this i just put $rootScope.online = false; when view content loaded like below :

// To set the view online message false.
$rootScope.$on('$viewContentLoaded', function() {
   $rootScope.online = false;
});

Preview :


If you like this post or you have any problem during implementation don't to leave a comment below i will definitely reply you back as soon as possible.


Chears :)
Happy coding..

Post a Comment

Previous Post Next Post