Goldbones
Goldbones

Reputation: 1457

Ionic 2 - Check Internet Connection on each request

I´m developping an app on Ionic 2 and I want to check internet connection for each request, i.e., I want to receive an instant message each time network is down or up.

My simple project will have :
page 1 - home (button to go to another page)
page 2 - another page

For that I´m using cordova plugin network information. From ionic 2 documentation:

import {Network, Connection} from 'ionic-native';

// watch network for a disconnect
let disconnectSubscription = Network.onDisconnect().subscribe(() => {
  console.log('network was disconnected :-( ')
});

// stop disconnect watch
disconnectSubscription.unsubscribe();


// watch network for a connection
let connectSubscription = Network.onConnect().subscribe(() => {
  console.log('network connected!');    
  // We just got a connection but we need to wait briefly
    // before we determine the connection type.  Might need to wait    
  // prior to doing any api requests as well.
  setTimeout(() => {
    console.log(Network.connection);
    if (Network.connection === Connection.WIFI) {
      console.log('we got a wifi connection, woohoo!');
    }
  }, 3000);
});

// stop connect watch
connectSubscription.unsubscribe();

The problem is that Network.onConnect().subscribe(() do not retrieve anything. It is the best way yo accomplish my goal?

Upvotes: 0

Views: 5113

Answers (1)

Naj
Naj

Reputation: 853

The problem with your code is that you are calling the unsubscribe method after you have subscribed for network changes. If you call connectSubscription.unsubscribe() you are telling ionic that now you don't care about changes in the network connection state. Remove the 2 unsubscribe methods and your code should be fine.

Also the subscribe and unsubscribe methods only listen for changes so to check for connectivity, use the comparison code directly.

if (Network.connection === 'wifi') {
    // do some api work
}

Let me know if it works.

Upvotes: 2

Related Questions