Check network connection?


#1

Hi, need some way to check for network connection, in browser you would use window.navigator.onLine but in ionic 1 it didn’t work because something related to the way cordova worked with the app, you would have to use a cordova plugin for it, how would you do it in ionic 2? is there a native ionic 2 directive for this or plugin from cordova? how would we make it work both during development (browser) and production?


#2

I’m using this way to check changes in the internet connection:

addConnectivityListeners() {
    var connectivity = this.connectivityService;
    window.addEventListener('online', function(e) {
        console.log("ONLINE");
        connectivity.callServerQueue();
    }, false);
    
     window.addEventListener('offline', function(e) {
        console.log("OFFLINE");
    }, false);
}

#3

Hi @victorcarvalhosp do this even work in device? as far as i know we have to use the cordova-plugin-network-information in order to test online status in mobile devices.


#4

This code only works with this plugin


#5

I describe how to make a “Connectivity” service in this tutorial: http://www.joshmorony.com/creating-an-advanced-google-maps-component-in-ionic-2/

It detects whether it is running on a device or through the browser and uses the best method for checking Internet connectivity.


#6

hey your function not worked…i tried ur code but it send always true.

code that i used

if(AllFunctions.isOnline(this.platform.is(‘Android’)))
{
console.log(‘test internt’);
this.getRepos();
}

static isOnline(onDevice): boolean {
if(onDevice && Network.connection){
return Network.connection !== Connection.NONE;
} else {
return navigator.onLine;
}
}


#7

Hi @joshmorony, thanks a lot for your code on your blog post, it’s clean. However the Typescript transpiler gives errors now.
Could you please update your code so it works with the latest ionic version (2.2.0).

Typescript Error
Property 'connection' does not exist on type 'typeof Network'.

#8

try with ‘type’ insted of ‘connection’


#9

hi everyone… i wonder if anyone is having the same problem as me (dont actually know if its a problem or normal behaviour).
I need to check connection on app resume, so I have a service with proper subscriptions to Platform.pause and Platform.resume and but when I try to access the network plugin on the onResume handler it comes undefined as everything I injected into the service constructor. I’m certainly missing something! Is this normal behaviour?


#10

Please post code. I’m skeptical that they’re really proper subscriptions.


#11

@rapropos I agree, if it’s not working I’m certainly missing something! thanks for the reply!

app.module.ts
import { Network } from ‘@ionic-native/network’;

@NgModule({
imports: [
IonicModule.forRoot(AppComponent, config),
IonicStorageModule.forRoot({
name: ‘__rsdb’,
driverOrder: [‘sqlite’, ‘indexeddb’, ‘websql’]
}),
BrowserModule,
HttpModule,
JsonpModule,
ReactiveFormsModule,
FormsModule,
TextMaskModule
],
declarations: declarations(),
entryComponents: entryComponents(),
providers: [
Config,
StatusBar, SplashScreen, Device, Network,
SQLite, SQLitePorter,
Title,
{provide: ErrorHandler, useClass: IonicErrorHandler},
NativeService, DBService, BaseService, UserService, DateService, PlanilhasService, ChecklistService
],
bootstrap: [IonicApp]
})

app.component.ts
import { NativeService } from ‘…/providers/native/native-service’;

constructor(
public platform: Platform,
public nativeService:NativeService
){}

native-service.ts
import { Injectable } from ‘@angular/core’;

import { Http, Headers, RequestOptions, Response } from ‘@angular/http’;
import { Observable } from ‘rxjs/Observable’;
import ‘rxjs/add/observable/throw’;
import ‘rxjs/add/operator/map’;
import ‘rxjs/add/operator/do’;
import ‘rxjs/add/operator/catch’;

import { Events, Platform } from ‘ionic-angular’;

import { StatusBar } from ‘@ionic-native/status-bar’;
import { SplashScreen } from ‘@ionic-native/splash-screen’;

import { Device } from ‘@ionic-native/device’;
import { Network } from ‘@ionic-native/network’;

import { Config } from ‘…/…/config/config’;

declare var cordova:any;
declare var navigator:any;
declare var Connection:any;

@Injectable()
export class NativeService {

ready:boolean = false;
isCordova:boolean;
isIOS:boolean;
isAndroid:boolean;

connType:string = '';
isOnline:boolean = false;

constructor(
	public config:Config,
	public http:Http,
	public events:Events,
	public plt:Platform,
	public statusBar:StatusBar,
	public splashScreen:SplashScreen,
	public device:Device,
	public network:Network
	){

	this.isAndroid = plt.is('android');
	this.isCordova = plt.is('cordova');
	this.isIOS = plt.is('ios');

	this.pltReady();
}

private pltReady(){
	this.plt.ready()
	.then((source)=>{

		this.ready = true;

		if(this.isCordova){
			this.connType = this.network.type;
			this.isOnline = false;
			this.eventsSubscribe();
		}
		
	})
	.catch(this.handleError);
}

private eventsSubscribe(){

	this.plt.pause.subscribe(this.onPause);
	this.plt.resume.subscribe(this.onResume);

	this.network.onchange().subscribe(this.onChange);
	this.network.onConnect().subscribe(this.onConnect);
	this.network.onDisconnect().subscribe(this.onDisconnect);
	
}

private onChange(){
	this.connType = this.network.type;
}
private onConnect(){
	this.connType = this.network.type;
}
private onDisconnect(){
	this.connType = this.network.type;
}


private onPause(){
	console.log('*******CORDOVA PAUSE*******');
}

private onResume(){
	console.log('******CORDOVA RESUME*******');
	setTimeout(()=>{
		this.connType = this.network.type;
	}, 3000);
}

private handleError(error){
	console.log('NATIVE SERVICE ONREADY ERROR: ', error);
}

}


#12

Yeah, that’s not going to work because you’re going to lose execution context. You can use bind or lambdas like so:

constructor() {
  let nethandler = () => {
    this.connType = this.network.type;
  };
  plt.ready().then(() => {
    network.onchange().subscribe(nethandler);
    network.onConnect().subscribe(nethandler);
    network.onDisconnect().subscribe(nethandler);
  });
}

#13

mmm interesting! I’ll try this approach to see if it works as i need because my problem is when the app resumes.

thanks a lot!


#14

In the documentation of the Network Information plugin you can see that the plugin emits 2 events: “offline” if the device goes offline and “online” if the devices goes online. These two events we can use to make Observables. In this HomePage i make 2 observables and in the subscribe i make functions to show Alerts. First I need the Observable from rxjs and the method fromEvent needs to be imported as well.


import {Page, Alert, NavController} from 'ionic-angular';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';

@Page({
    templateUrl: 'build/pages/home/home.html'
})
export class HomePage {

constructor(public nav:NavController) {
    var offline = Observable.fromEvent(document, "offline");
    var online = Observable.fromEvent(document, "online");

    offline.subscribe(() => {
        let alert = Alert.create({
            title: "Connection",
            message: "You are offline!"
        });
        nav.present(alert);
    });

    online.subscribe(()=>{
        let alert = Alert.create({
            title: "Connection",
            message: "You are online!"
        });
        nav.present(alert);
    });
  }
}

this way you can check network dynamically in your ionic 2 application


#15

Thats a very nice solution!
I’ve seen people trying to use document.addEventListener on Ionic 2 projects and it won’t work!

What worked for me was this:
the connHandler inside the constructor as a lambda
and on platform.ready I subscribe to onchange, connect and disconnect

but honestly I prefer the events from the actual cordova plugin

@Injectable()
export class NativeService {

	ready:boolean = false;
	isCordova:boolean;
	isIOS:boolean;
	isAndroid:boolean;

	connType:string = '';
	isOnline:boolean = false;

	constructor(
		public config:Config,
		public http:Http,
		public events:Events,
		public plt:Platform,
		public statusBar:StatusBar,
		public splashScreen:SplashScreen,
		public device:Device,
		public network:Network,
    	public keyboard:Keyboard
		){

		this.isAndroid = plt.is('android');
    	this.isCordova = plt.is('cordova');
    	this.isIOS = plt.is('ios');

    	let connHandler = (evt)=>{
    		//console.log('****** CONN CHANGED *******', evt.type);
    		this.connType = network.type;
    		if(evt.type == 'online') this.isOnline = true;
    		else this.isOnline = false;
    	}

    	plt.ready()
		.then((source)=>{

			this.ready = true;

			if(this.isCordova){

            	this.keyboard.hideKeyboardAccessoryBar(true);
            	this.keyboard.onKeyboardShow().subscribe(evt=>{
            		console.log(evt);
            	});
            	this.keyboard.onKeyboardHide().subscribe(evt=>{
            		console.log(evt);
            	});

				this.connType = network.type;
				if(network.type != 'none') this.isOnline = true;

				this.network.onchange().subscribe(connHandler);
				this.network.onConnect().subscribe(connHandler);
				this.network.onDisconnect().subscribe(connHandler);
				
				this.plt.pause.subscribe(()=>{
					//console.log('*******CORDOVA PAUSE*******');
				});

				this.plt.resume.subscribe(()=>{
					console.log('******CORDOVA RESUME*******');
					setTimeout(()=>{
						this.connType = this.network.type;
						console.log('******ON RESUME CONN TYPE******', this.connType);
					}, 3000);
				});
			}
			
		})
		.catch(this.handleError);
	}

	private handleError(error){
		console.log('NATIVE SERVICE ONREADY ERROR: ', error);
	}
}

#16

It is easy!!

This is my app.components.ts

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

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

export class MyApp {
  constructor(
    private network: Network,
    public 	platform:  Platform,
  ) {
    // Call it when the device is ready, calling before drops null
    platform.ready().then(() => {
      // if no internet, notice is a string
      if (this.network.type == 'none' ) { 
        // stuff if disconnected
      } else {
        //stuff if connected
      }
    })
  }
}

#17

Service Class Code

Service Class code is this

declare var Connection;
@Injectable()
export class ConnectivityService {

constructor(public platform: Platform, public alertCtrl: AlertController, private network:Network) {

}

isOnline(): boolean {
console.log('Network connection is : ’ + this.network.type);

if(this.network.type !== 'none'){
  return true;
}else if(this.network.type === 'none'){
  alert('Please Check your network and try again');
}else{
  alert('Please Check your network and try again');
}

}
}

Usage in .ts file(Your page)

import { Network } from ‘@ionic-native/network’;
import { ConnectivityService } from ‘…/…/providers/connectivity-service’;

constructor(public navCtrl: NavController, public navParams: NavParams,
private platform: Platform,private network: Network,
private connectivityService:ConnectivityService ) {

goToNext(){
if(this.connectivityService.isOnline()){
// Network Connection available
this.navCtrl.push(SecondPage);
}
else{
// Network Connection not available
alert(‘Check your Network connection’);
}
}

}


#18

super it work for me


#20

After internet get disconnected, I want to display alert message until user have active network connection.
How to do that?