Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I detect internet connection at runtime in ionic2 app?

I really need your help please. I'm trying to detect if there is internet connectivity on my Ionic 2 mobile app. I need to know at any time if the mobile lost connection and when it recovers it, also if there is wifi connection.. so the observators and the wifi detection of the Network Cordova plug-in, just does what I need For achieve that, I have two suscribers (for connection and disconnection) in the page constructor to set an boolean instance variable I used throught out the page logic. Here is my code

app.component.ts

import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';

import { HomePage } from '../pages/home/home';
import { Geolocation } from '@ionic-native/geolocation';
import { Network } from '@ionic-native/network';
//import { Network } from 'ionic-native';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

 @NgModule({
    declarations: [
      MyApp,
      HomePage
    ],
    imports: [
      IonicModule.forRoot(MyApp)
    ],
    bootstrap: [IonicApp],
    entryComponents: [
       MyApp,
       HomePage    
    ],
    providers: [
      StatusBar,
      SplashScreen,
      {provide: ErrorHandler, useClass: IonicErrorHandler},    
      Geolocation,
      Network
   ]
  })
  export class AppModule {}




home.ts

import { Component } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
import { Network } from '@ionic-native/network';


@Component({
 selector: 'page-home',
 templateUrl: 'home.html'
})
 export class HomePage {

private online:boolean = false;
private wifi:boolean = false;
public disconnectSubscription:any;
public connectSubscription:any;

constructor(private nav: NavController, private geolocation: Geolocation, private network: Network, private platform: Platform) {  
    this.platform.ready().then( () => {
      //listener
      this.connectSubscription = this.network.onConnect().subscribe(() => {
          alert('connected!');
          this.online = true;

          setTimeout(() => {
            // before we determine the connection type.  Might need to wait
            if (this.network.type === 'wifi') {
              this.hayWIFI;
              alert('wifi connection');
            }
          }, 3000);
      });

      //listener
      this.disconnectSubscription = this.network.onDisconnect().subscribe(() => {            
          this.online = false;
          alert('without connection!');
      });
    });
}

}

The problem is that the events are triggered like a onchange event.. I only see the alerts when I manually take out the connection of the mobile or when the app is recovering from sleeping (when it has lost the connection), but not when the app just initializes :( I have tried the constructor suscriptors' at the home page and even at the MyApp page (app.component.ts) without success

What am I doing wrong? How can I achive the requirements? There are many diferent approches on the internet but look older and differ even in the import of the Network Service. My ionic info is

Ionic Framework: 2.3.0
Ionic App Scripts: 1.1.4
Angular Core: 2.4.8
Angular Compiler CLI: 2.4.8
Node: 6.4.0
OS Platform: Windows 10
Navigator Platform: Win32
User Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36

thanks in advance

like image 698
jmann Avatar asked Jan 04 '23 03:01

jmann


1 Answers

If you want to listen to network statuses in a component (page) I'd suggest doing that inside one of the page lifecycle events, like ionViewDidLoad() or ionViewDidEnter(). Generally, you want to make sure your constructor is handling as little logic as possible since it will only fire once. You can read more about them here.

In my app, I'm listening for network status in a provider that serves as a wrapper for the Angular HTTP module. To get this to work, I had to initialize all of my logic inside of a platform.ready() block to make sure that the device was actually ready to start being manipulated. Here's what my provider looks like:

export class HTTP {
  public online:boolean = true;
  public base:string; // this will be set in the constructor based on if we're in dev or prod
  public token:string = null;

  constructor(public platform:Platform, public http: Http, public events:Events, public cache:CacheService, private network:Network) {
    if(document.URL.includes('https://') || document.URL.includes('http://')){
      this.base = "http://127.0.0.1:3001/";
    } else {
      this.base = "https://url.to_actual_URL.com/";
    }

    this.platform.ready().then(() => {
      let type = this.network.type;

      //console.log("Connection type: ", this.network.type);
      // Try and find out the current online status of the device
      if(type == "unknown" || type == "none" || type == undefined){
        //console.log("The device is not online");
        this.online = false;
      }else{
        //console.log("The device is online!");
        this.online = true;
      }
    });

    this.network.onDisconnect().subscribe( () => {
      this.online = false;
      //console.log('network was disconnected :-(');
    });

    this.network.onConnect().subscribe( () => {
      this.online = true;
      //console.log('network was connected :-)');
    });
  }
}
like image 196
TheBrockEllis Avatar answered Jan 13 '23 10:01

TheBrockEllis