How to check offline and online in angular
I suggest you use Offline.js
they have templates and other materials to work with. you can check their documentation and see how it works.
it gets your current connection state by returning an "up" or "down" result, or you can bind it to an event and use it in your application.
here's what they say about their library:
Offline.js is a library for automatically alerting users when they have lost their internet connection, such as Gmail.
It captures the AJAX requests that were made during the connection and rewires them when it is backed up, so your application is responsive.
It has many beautiful themes and doesn't require any customization.
good luck and have fun.
source to share
Check navigator.onLine
and, based on this value, decide whether or not to send the request.
if (navigator.onLine) {
$http.get('url').success(function() {});
}
else {
// no req
}
Angular way:
Use a Service $q
- A service that helps you execute functions asynchronously and use their return values (or exceptions) when they are processed. https://docs.angularjs.org/api/ng/service/ $ q
The best way I would know would be to intercept the HTTP handler if its 401/501 / etc. then process it according to
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 is listening on, just add
$rootScope.$on("ServerError", someServerErrorFunction);
Source: How To Determine When Online / Offline Status Changes
source to share