I want to know when internet connection is lost and regained, so that I can toggle between an alert saying \"whoops, no internet\" and a Google map or a grid containing data
In my applications, I have a /ping endpoint that I poll every X seconds. This of course may not be suitable for large-scale apps.
angular.module("pingMod", [])
.run(function ($http, $interval) {
var TIME = 60000;
function ping() {
$http.get("/ping");
}
$interval(ping, TIME);
});
I use this in combination with what @Gil suggested, an HTTP interceptor. When we get a 0 status, we are offline. This is triggered for any AJAX call that uses $http.
Here is code for the interceptor using $http. You may of course decide you want to use Restangular instead, but it depends on your app needs.
angular.module("myModule", [])
.config(function ($httpProvider) {
var interceptor = [
'$q',
function ($q) {
return function (promise) {
return promise.then(function (response) {
return response;
}, function (response) {
if (response.status === 0) {
// We're offline!
}
return $q.reject(response);
});
};
}];
$httpProvider.responseInterceptors.push(interceptor);
})