How can I detect internet connection at runtime in ionic2 app?
I really need your help. I am trying to determine if there is an internet connection in my Ionic 2 mobile app. I need to know at any time if the mobile connection is lost and when it re-establishes it, also if there is a wifi connection .. so observers and wifi detection of the plugin Network Cordova just do what I need To do this I have two callers (to connect and disconnect) in the page constructor to set the boolean instance variable that I used in 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 events are fired as an onchange event. I only see warnings when I manually unplug the mobile phone connection, or when the app recovers from sleep (when it lost the connection) , but not when the app just initializes :( I tried constructor supporters on the home page and even the MyApp page (app.component.ts) no success
What am I doing wrong? How can I fulfill the requirements? There are many different approaches on the Internet, but they look older and differ even from importing a Net Service. My ionic information
Ionic base: 2.3.0
Ionic application scripts: 1.1.4
Angular Kernel: 2.4.8
Angular CLI compiler: 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
early
source to share
If you want to listen for network states in a component (page), I would suggest doing it inside one of the page lifecycle events like ionViewDidLoad()
or ionViewDidEnter()
. Typically, you want to make sure that your constructor handles as little logic as possible, since it will only fire once. You can read more about them here .
In my application, I am listening for network status from a provider that wraps the Angular HTTP module. To get this to work, I had to initialize all my logic inside the block platform.ready()
to make sure the device was really ready to start manipulating. This is 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 :-)');
});
}
}
source to share
I solved a similar problem using ngcordova . It provides an angular wrapper around a plugin that implements promises.
Often Cordova plugins are not ready, when you try to call them using the promises interface you can avoid undefined errors.
I stole an example from the ngcordova page in the network plugin here.
module.controller('MyCtrl', function($scope, $rootScope, $cordovaNetwork) {
document.addEventListener("deviceready", function () {
var type = $cordovaNetwork.getNetwork()
var isOnline = $cordovaNetwork.isOnline()
var isOffline = $cordovaNetwork.isOffline()
// listen for Online event
$rootScope.$on('networkOffline', function(event, networkState){
var onlineState = networkState;
})
// listen for Offline event
$rootScope.$on('networkOffline', function(event, networkState){
var offlineState = networkState;
})
}, false);
});
source to share