Skip to content

Instantly share code, notes, and snippets.

@mckennatim
Created August 28, 2014 18:40
Show Gist options
  • Save mckennatim/b60629760aebd2081a5f to your computer and use it in GitHub Desktop.
Save mckennatim/b60629760aebd2081a5f to your computer and use it in GitHub Desktop.
ng-online Checking online status in AngularJS app // source http://jsbin.com/lesoru/1
<meta name="description" content="Checking online status in AngularJS app" />
<title>ng-online</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.14/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.10.0/ui-bootstrap-tpls.min.js"></script>
<script src="main.js"></script>
<body ng-app="App">
<div ng-controller="AppController">
<span class="glyphicon glyphicon-signal" ng-show="online"></span>
<span class="glyphicon glyphicon-ban-circle" ng-show="!online"></span>
{{dog}}<br>
online: {{online}}<br>
<input type="text" name="" ng-model="dog" placeholder=""><br>
<input type="button" name="" value="change fred" ng-click="change()">
<input type="button" name="" value="{{running}}" ng-click="toggle()">
</div>
<script id="jsbin-javascript">
var app = angular.module("App", []);
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('Interceptor');
});
app.run(function(Factory, $rootScope){
console.log('running')
Factory.ckIfOnline();
})
app.factory('Factory', function($q, $http, $rootScope){
var httpLoc = 'http://parleyvale.com:3000/api/';
return{
ckIfOnline: function(){
$http.get(httpLoc);
},
change: function(){
return 'duck'
}
}
})
app.factory('Interceptor', function($rootScope){
var Interceptor ={
responseError: function(response){
$rootScope.status = response.status;
$rootScope.online = false;
return response;
},
response: function(response){
$rootScope.status = response.status;
$rootScope.online = true;
return response;
}
};
return Interceptor;
})
app.controller("AppController", function($scope, Factory, $rootScope, $interval){
var running;
$scope.running='toggle server polling '
console.log($rootScope.online)
$scope.online = $rootScope.online
$scope.dog="fred";
$scope.change =function(){
$scope.dog=Factory.change()
}
Factory.ckIfOnline();
$rootScope.$watch('online', function(newValue, oldValue){
if (newValue !== oldValue) {
$scope.online=$rootScope.online;
}
});
var runUpd = function(){
running = $interval(function(){
console.log('running update')
Factory.ckIfOnline();
},5000);
};
var cancelRunning = function() {
if (running) {$interval.cancel(running);}
};
//runUpd();
$scope.toggle=function(){
if (running) {
$interval.cancel(running);
running=null;
$scope.running='not polling server';
}else{
$scope.running='polling server';
running = $interval(function(){
console.log('running update')
Factory.ckIfOnline();
},5000);
}
}
});
</script>
<script id="jsbin-source-html" type="text/html"> <meta name="description" content="Checking online status in AngularJS app" />
<title>ng-online</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.14/angular.min.js"><\/script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.10.0/ui-bootstrap-tpls.min.js"><\/script>
<script src="main.js"><\/script>
<body ng-app="App">
<div ng-controller="AppController">
<span class="glyphicon glyphicon-signal" ng-show="online"></span>
<span class="glyphicon glyphicon-ban-circle" ng-show="!online"></span>
{{dog}}<br>
online: {{online}}<br>
<input type="text" name="" ng-model="dog" placeholder=""><br>
<input type="button" name="" value="change fred" ng-click="change()">
<input type="button" name="" value="{{running}}" ng-click="toggle()">
</div>
</body></script>
<script id="jsbin-source-javascript" type="text/javascript">var app = angular.module("App", []);
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('Interceptor');
});
app.run(function(Factory, $rootScope){
console.log('running')
Factory.ckIfOnline();
})
app.factory('Factory', function($q, $http, $rootScope){
var httpLoc = 'http://parleyvale.com:3000/api/';
return{
ckIfOnline: function(){
$http.get(httpLoc);
},
change: function(){
return 'duck'
}
}
})
app.factory('Interceptor', function($rootScope){
var Interceptor ={
responseError: function(response){
$rootScope.status = response.status;
$rootScope.online = false;
return response;
},
response: function(response){
$rootScope.status = response.status;
$rootScope.online = true;
return response;
}
};
return Interceptor;
})
app.controller("AppController", function($scope, Factory, $rootScope, $interval){
var running;
$scope.running='toggle server polling '
console.log($rootScope.online)
$scope.online = $rootScope.online
$scope.dog="fred";
$scope.change =function(){
$scope.dog=Factory.change()
}
Factory.ckIfOnline();
$rootScope.$watch('online', function(newValue, oldValue){
if (newValue !== oldValue) {
$scope.online=$rootScope.online;
}
});
var runUpd = function(){
running = $interval(function(){
console.log('running update')
Factory.ckIfOnline();
},5000);
};
var cancelRunning = function() {
if (running) {$interval.cancel(running);}
};
//runUpd();
$scope.toggle=function(){
if (running) {
$interval.cancel(running);
running=null;
$scope.running='not polling server';
}else{
$scope.running='polling server';
running = $interval(function(){
console.log('running update')
Factory.ckIfOnline();
},5000);
}
}
});
</script></body>
var app = angular.module("App", []);
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('Interceptor');
});
app.run(function(Factory, $rootScope){
console.log('running')
Factory.ckIfOnline();
})
app.factory('Factory', function($q, $http, $rootScope){
var httpLoc = 'http://parleyvale.com:3000/api/';
return{
ckIfOnline: function(){
$http.get(httpLoc);
},
change: function(){
return 'duck'
}
}
})
app.factory('Interceptor', function($rootScope){
var Interceptor ={
responseError: function(response){
$rootScope.status = response.status;
$rootScope.online = false;
return response;
},
response: function(response){
$rootScope.status = response.status;
$rootScope.online = true;
return response;
}
};
return Interceptor;
})
app.controller("AppController", function($scope, Factory, $rootScope, $interval){
var running;
$scope.running='toggle server polling '
console.log($rootScope.online)
$scope.online = $rootScope.online
$scope.dog="fred";
$scope.change =function(){
$scope.dog=Factory.change()
}
Factory.ckIfOnline();
$rootScope.$watch('online', function(newValue, oldValue){
if (newValue !== oldValue) {
$scope.online=$rootScope.online;
}
});
var runUpd = function(){
running = $interval(function(){
console.log('running update')
Factory.ckIfOnline();
},5000);
};
var cancelRunning = function() {
if (running) {$interval.cancel(running);}
};
//runUpd();
$scope.toggle=function(){
if (running) {
$interval.cancel(running);
running=null;
$scope.running='not polling server';
}else{
$scope.running='polling server';
running = $interval(function(){
console.log('running update')
Factory.ckIfOnline();
},5000);
}
}
});
@mckennatim
Copy link
Author

Checking online status in AngularJS app

Often apps can do useful work while offline. While online and connected to the server additional functionality is enabled. It is helpful to know if a device is connected to the internet and if its server is available.

You might as well check online status every time your app makes an http request. If you wanted to periodically update your online status you could make a simple http request and intercept its response to set the state of a $rootscope variable that could then be watched by any controller.

Intercepting http calls, setting some rootScope variables and watching them from a controller, and polling the server periodically to update everything are the steps described below.

Intercepting http calls

Interceptors are set up in the app.config and coded in a factory.

  var app = angular.module("App", []);

  app.config(function ($httpProvider) {
      $httpProvider.interceptors.push('Interceptor');
  });

Inject $rootScope and set variables:

  app.factory('Interceptor', function($rootScope){
          var Interceptor ={
              responseError: function(response){
                  $rootScope.status = response.status;
                  $rootScope.online = false;
                  return response;
              },
              response: function(response){
                  $rootScope.status = response.status;
                  $rootScope.online = true;
                  return response;
              }
          };
          return Interceptor;
  })

btw: $window.navigator.onLine would tell you if your device is online but not if the server is.

watching $rootScope variables

You can watch rootscape variables for your controller and use it to modify something in the contorller's scope.

  $rootScope.$watch('online', function(newValue, oldValue){
      if (newValue !== oldValue) {
          $scope.online=$rootScope.online;
      }
  });

interval polling of the server

The fiddle has a button that toggles the $interval timer either on or off. When on it runs ckIfOnline every 5 seconds.

  $scope.toggle=function(){
      if (running) {
          $interval.cancel(running);
          running=null;
          $scope.running='not polling server';
      }else{
          $scope.running='polling server';
          running = $interval(function(){
          console.log('running update')
          Factory.ckIfOnline();
      },5000); 
      }
  }

check ifOnline

Any http call will tell you if your device is online or not. A simple call to your rest server will tell you if you are online and if your server is online. A factory is a good place for this function.

    app.factory('Factory', function($q, $http, $rootScope){
        var httpLoc = 'http://google.com'; 
        return{
            ckIfOnline: function(){
                $http.get(httpLoc);                      
            },  
        }
    })

You don't need any callbacks or promises for the http calls or the interceptor. Whenever they do come back they will set the $rootScope variable and whenever they get set the local watchers will react.

demo

plnkr. gist. jsbin In 'Factory' you can set the url for any server you want. Otherwise just take your browser offline while polling and you should see the app go offline.

tags: interceptors, polling, $interval, $watch, $rootScope, $httpProvider

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment