How to detect when online/offline status changes

前端 未结 3 1898
慢半拍i
慢半拍i 2020-12-23 02:11

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

3条回答
  •  臣服心动
    2020-12-23 02:17

    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);
    })
    

提交回复
热议问题