问题
I have been getting an error from the service call when browse is in offline mode. How can check off-line mode and want to block my service call when the browser is the offline mode?
回答1:
I suggest you to use Offline.js
they have templates and other stuff to work with . you can check out their documentation and see how it works .
it gets you the current state of the connection by returning the "up" or "down" result , or you can bind and event to it and use it across you'r application .
this is what they say about their library :
Offline.js is a library to automatically alert your users when they've lost internet connectivity, like Gmail.
It captures AJAX requests which were made while the connection was down, and remakes them when it's back up, so your app reacts perfectly.
It has a number of beautiful themes and requires no configuration.
good luck and have fun.
回答2:
Check for navigator.onLine
and based on this value decide whether to send request or not.
if (navigator.onLine) {
$http.get('url').success(function() {});
}
else {
// no req
}
Angular way:
Use $q
service - A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing. https://docs.angularjs.org/api/ng/service/$q
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
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);
Source: How to detect when online/offline status changes
来源:https://stackoverflow.com/questions/30543426/how-can-check-offline-and-online-in-angular