Dick Swart
Dick Swart

Reputation: 141

Online and offline event are firing twice

Can someone please help?

I trying to check when internet conectivity is lost in my ionic project, It is working fine but the event fires twice in a row for some reason. below is my code in my app.js in $ionicPlatform.ready:

if (window.Connection) {

   $rootScope.$on('$cordovaNetwork:online', function (event, networkState) {
       console.log('We Are Online');
   });

   $rootScope.$on('$cordovaNetwork:offline', function (event, networkState) {
       console.log('We Are Offline');
   });
}

Like I said it works but fires twice in a row, so when I want to display a popup when internet connection is lost it is displayed twice.

I checked the ionic forum and found a guy with a similar problem but no one really gave him an exact answer: http://forum.ionicframework.com

Upvotes: 2

Views: 1471

Answers (2)

systemdebt
systemdebt

Reputation: 4941

SharpEdge has provided a pretty good workaround.

You can also use angular's $watch service to check for the change in boolean value and it works pretty well.

Also, There are 2 neat workarounds here at this link: http://www.yourtechchick.com/cordovanetwork-online-and-offline-events-fired-twice/

Upvotes: 0

SharpEdge
SharpEdge

Reputation: 1762

This is a workaround using a state dummy var

var isOnline = true;

if (window.Connection) {

   $rootScope.$on('$cordovaNetwork:online', function (event, networkState) {
     if(isOnline) return;
     
     isOnline = true;
     
     console.log('We Are Online');
   });

   $rootScope.$on('$cordovaNetwork:offline', function (event, networkState) {
       if(!isOnline) return;
     
       isOnline = false;
     
       console.log('We Are Offline');
   });
}

Upvotes: 7

Related Questions