4

Using AngularJS, how can I display an alert message status if I lose an internet connection in my app?

I am working on Angularjs Express framework and APIs. while working on app if I lose internet connection I need to pop up an alert and I should stop calling HTTP requests until I receive a proper internet connection and resume the work.

I even tried with offline.js am not able to solve please if any simple and easy method is there let me know thank you. In header I added all these

<script src="/javascripts/plugins/offlinechecking/offline.min.js"></script>
<link rel="stylesheet" href="/stylesheets/themes/offline-theme-chrome.css" />
<link rel="stylesheet" href="/stylesheets/themes/offline-language-english.css" />
<script>
  Offline.options = {
    checkOnLoad: false,
    interceptRequests: true,
    reconnect: {
      initialDelay: 3,
      delay: (1.5 * last delay, capped at 1 hour)
    },
    requests: true,
    game: false
</script>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Ambika KU
  • 91
  • 6

2 Answers2

2

You can use online and offline events:

app.run(function($window, $rootScope) {
      $rootScope.online = navigator.onLine;
      $window.addEventListener("offline", function () {
        $rootScope.$apply(function() {
          $rootScope.online = false;
        });
      }, false);
      $window.addEventListener("online", function () {
        $rootScope.$apply(function() {
          $rootScope.online = true;
        });
      }, false);
});

More info: How to check internet connection in AngularJs

Moreover, you didn't close your Offline.options object:

Offline.options = {
// No closing }.
Community
  • 1
  • 1
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

Your options:

  • addEventListener on the window, document, or document.body.

  • setting the .ononline or .onoffline properties on document or
    document.body to a JavaScript Function object.

  • specifying ononline="..." or onoffline="..." attributes on the
    tag in the HTML markup

I will demonstrate the easiest.

In you controller

document.body.onoffline = function() {
   alert('You are offline now');
   $scope.connection = 'offline' 
}

document.body.ononline = function() {
   alert('You are online again');
   $scope.connection = 'online' 
}

Check $scope.connection variable before you try to send requests around.


Update for Comment1

If you need the variable to be global, set it in a factory

myApp.factory('connectionStatus', function(){
   var connection;

   return connection;
})

Now inject this factory wherever you need to use it. This is how it goes inside your main controller where you set the events.

myApp.controller('mainController', function($scope, connectionStatus) {
    document.body.onoffline = function() {
           alert('You are offline now');
           connectionStatus = 'offline' 
    }
})
Charlie
  • 22,886
  • 11
  • 59
  • 90