0
votes

I know how to check device ready in jQuery. But it is bad practice to use jQuery along with Angular. So, I am planning not to use jQuery in Angular.

I want to test device ready event. In jQuery below code works:

<script type="text/javascript">
    document.addEventListener("deviceready", onDeviceReady, false);
    
    function onDeviceReady() {
        var deviceID = device.uuid;

        $(document).ready(function() {
            document.addEventListener("offline", onOffline, false);
        });
    
        function onOffline() {
            location.href = "no_network.html";
        }   
    }
</script>

How can I do the same in Angularjs?

1

1 Answers

1
votes

Just add the event listener in a service constructor or in your bootstrapping routine.

Sticking with your example a service to manage the applications network status could look like this in Typescript:

class NetworkStatusService {
    deviceIsOnline: boolean;

    constructor() {
        document.addEventListener("deviceready", () => {
            if (navigator.connection.type === Connection.NONE) {
                this.deviceIsOnline = false;
            } else {
                this.deviceIsOnline = true;
            }
        });

        document.addEventListener("offline", () => {
            this.deviceIsOnline = false;
        });
        document.addEventListener("online", () => {
            this.deviceIsOnline = true;
        });
    }
}

Adding corresponding Javascript snippet for convinience ;)

var NetworkStatusService = (function () {
    function NetworkStatusService() {
        var _this = this;
        document.addEventListener("deviceready", function () {
            if (navigator.connection.type === Connection.NONE) {
                _this.deviceIsOnline = false;
            }
            else {
                 _this.deviceIsOnline = true;
            }
        });
        document.addEventListener("offline", function () {
            _this.deviceIsOnline = false;
        });
        document.addEventListener("online", function () {
            _this.deviceIsOnline = true;
        });
    }
    return NetworkStatusService;
}());