Arash
Arash

Reputation: 3688

ionic checking network connection before any action

i have an ionic app with totally 20 page , on each page there is a request to server , most of them are post request ,

is there any way in iconic cordova app , to check network connection and alerting user that that there is no network connection if there is no network connection ?

i can check this in every controller , but i am looking for global handling of this checking .

below is sample action in controller

$scope.sendMessageToManager = function () {
        $ionicLoading.show({ template: '<ion-spinner></ion-spinner>' })
        $http.post(serverConfig.serverUrl + '/api/services/app/hrService/SendMessageToManager', $scope.message).success(function () {
            $ionicLoading.hide();
            $scope.showAlert();
            $scope.message = {};
        })
    }

how can i check network connection before calling sendMessageToManager() ?

is there any specific pattern or guideline for this in cordova ?

thanks.

Upvotes: 0

Views: 1251

Answers (3)

Gene
Gene

Reputation: 2218

Following up the answer from Aung Myat Hein, you need to get the cordova-plugin-network-information.

cordova plugin add cordova-plugin-network-information

In which if you need a simple way, u can set it into your localstorage.

For offline handling:

    document.addEventListener("offline", function()
    {
        console.log("in offline event listener");
        self.events.publish('internetStatus', 'off');
        this.local.set("internet", "off"); //sets the localstorage
    }, false);

for online handling it would be:

    document.addEventListener("online", function()
    {
        console.log("in online event listener");
        self.events.publish('internetStatus', 'on');
        this.local.set("internet", "on"); //sets the localstorage
    }, false);

No matter where you are at, before calling your HTTP requests, you can do a check by getting the value of the key( in this case, internet) from the local storage.

Upvotes: 0

Aung Myat Hein
Aung Myat Hein

Reputation: 4188

Use cordova-plugin-network-information, to check network connection in ionic.

cordova plugin add cordova-plugin-network-information

When running on device, you can check.

$cordovaNetwork.isOnline();

Joshmorony wrote tutorial about it. HERE

Upvotes: 1

Ipe Himanshu
Ipe Himanshu

Reputation: 51

You can use event into your app.js

like

document.addEventListener("offline", function(e) { //$state.go('offline', {}, {reload: true}); alert('No Internet'); }, false);

Upvotes: 0

Related Questions