Search code examples
cordovaionic-frameworkionic3hybrid-mobile-appionic-native

Ionic Network don't return any data or response


I am trying to check the internet/network connection of the device using Network Plugin but it doesn't seem to work. It didn't even return any data or error messages on the console. Here is my code.

import { Network } from '@ionic-native/network';

@Component({
  templateUrl: 'app.html'
})

export class MyApp {

  constructor(public platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar
    public network: Network) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      this.checkInternetConnection();
    }
  }


  checkInternetConnection() {
    this.network.onDisconnect().subscribe(data => {
      console.log('network was disconnected :-(');
    }, error => console.log(error));

    this.network.onConnect().subscribe(data => {
      console.log('network connected!');
      setTimeout(() => {
        console.log('woohoo!');
      }, 3000);
    }, error => console.log(error));
  }
}

I hope someone can help me. Thank you in advance 😊


It is working now but it only triggers when I open the app then turn off the wifi but if the wifi was already turned off before I open the app it won't work anymore. I don't know how to trigger that after showing the splash screen.


Solution

  • this two observable fire on state change , so if you want to check the connection on start you have to look if the network is present like that

    if(network.type == network.Connection.NONE) {

    console.log('network was disconnected :-(');

    } else{

    console.log('network connected!');

    }

    you can keep the observable for the network change, when the app is running