Reputation: 40145
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 derived from my server.
This related question and this other related question think that they have the answer, but they do not.
Their solution works with Chrome Version 34.0.1847.137 m, MS IE v11.0.x.x, but NOT with FireFox v29.0.1, so I am seeking a solution which works with all of those three browsers.
[Update] AS @Quad points out there are different ways of defining what it means to be online. I am definign it as "can I fetch the data which I need to show to my user or not?".
I have several services, which are responsible for fetching data from several servers (what's best? A single, parameterized, service? One service per server? Or one service per type of data per server? I am thinking the latter, as each service can then map to a controller which maps to a view. But I am new to Angular, so may well be wrong).
Additionally, I had coded a service which is responsible for attempting to reconnect when connection is lost.
Anyone who tries an $http.get
and gets 404 can invoke the service which would
1) broadcast that there was no internet (so that no one else would try to connect)
2) regularly attempt to connect to my server and
3) when successful, stop the connection attempts and broadcast that the app is now online again.
However, that seemed very klunky and the solution offered in the two related questions seemed elegant - except for FF :-(
I cannot be reinventing the wheel here. How do others do it? In fact, I am surprised that there is not already an "official" Angular solution
Upvotes: 26
Views: 27161
Reputation: 1244
The best way that I would know would be to intercept the HTTP handler, if its a 401 / 501/ etc then to handle it according
ex:
angular.module('myApp', ['myApp.services'],
function ($httpProvider) {
var interceptor = ['$rootScope', '$q', function ($rootScope, $q) {
function success(response) {
return response;
}
function error(response) {
var status = response.status; // error code
if ((status >= 400) && (status < 500)) {
$rootScope.broadcast("AuthError", status);
return;
}
if ( (status >= 500) && (status < 600) ) {
$rootScope.broadcast("ServerError", status);
return;
}
// otherwise
return $q.reject(response);
}
return function (promise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);
then in your code that listens for the on of, just add in
$rootScope.$on("ServerError", someServerErrorFunction);
You could also add an internal flag and broadcast only when that flag changed.
But if you are looking for a solution where the user is not communicating with the server too frequently, you could add a section that pings the server every minute or so, but that may not be responsive as you like.
Upvotes: 26
Reputation: 35920
You can detect disconnect either by polling your server, or just waiting for a failed response. The latter approach is preferable unless you have special requirements. Once a disconnect is detected, you will need to use polling to detect re-connection.
An elegant way to implement this in angular is to monitor all network activity with $http
, the injectable service through which all XHR activity flows. Restangular abstracts this out for you with:
RestangularProvider.addFullRequestInterceptor
: Gives you full access to the request before sending any data to the server.
RestangularProvider.setErrorInterceptor
: Called after each error response from the server.
Here is the pseudo-code to implement a status watcher using Restangular:
var last_request
RestangularProvider.addFullRequestInterceptor:
last_request = Save last request
RestangularProvider.setErrorInterceptor:
- Display the 'offline' status message to user
- Use $interval to periodically re-submit last_request until successful
- When periodic re-submission succeeds, hide 'offline' status message
Even though you didn't specifically ask for an answer utilizing Restangular, you did say you were looking for an established pattern and Restangular has some very easy-to-use yet powerful patterns built-in. Of course the same idea presented here could instead be implemented with just $http
.
Upvotes: 5
Reputation: 1841
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);
})
Upvotes: 7