How can check offline and online in angular

家住魔仙堡 提交于 2019-12-06 03:53:40

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.

softvar

Check for navigator.onLineand 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!