Ionic 3 network connectivity check how to implement for all pages (components)?


#1

Dear Friends,
I need to check internet connectivity as well as actual access if connection already exist. I prefer a dialog with ok and settings. If click settings redirect to network settings page … I can understand that https://ionicframework.com/docs/native/network/ do the stuff . I prefer a working sample for same…

Thanking you

Anes


#2

Hi, @anespa

Here is sample code for check internet connectivity when your app is online or offline.

First, you need to create network provider and add following code,

import { Injectable } from '@angular/core';
import { AlertController, Events } from 'ionic-angular';
import { Network } from '@ionic-native/network';

export enum ConnectionStatusEnum {
    Online,
    Offline
}


@Injectable()
export class NetworkProvider {

  previousStatus;

  constructor(public alertCtrl: AlertController, 
              public network: Network,
              public eventCtrl: Events) {

    console.log('Hello NetworkProvider Provider');

    this.previousStatus = ConnectionStatusEnum.Online;
    
  }

    public initializeNetworkEvents(): void {
        this.network.onDisconnect().subscribe(() => {
            if (this.previousStatus === ConnectionStatusEnum.Online) {
                this.eventCtrl.publish('network:offline');
            }
            this.previousStatus = ConnectionStatusEnum.Offline;
        });
        this.network.onConnect().subscribe(() => {
            if (this.previousStatus === ConnectionStatusEnum.Offline) {
                this.eventCtrl.publish('network:online');
            }
            this.previousStatus = ConnectionStatusEnum.Online;
        });
    }

}

Now add this code to app.component file when initializing your app,

import { Component } from '@angular/core';
import { Platform,  Events } from 'ionic-angular';
import { Network } from '@ionic-native/network';
import { NetworkProvider } from '../providers/network/network';

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

export class MyApp {

        constructor(public platform: Platform, 
                    public events: Events,
                    public network: Network,
                    public networkProvider: NetworkProvider) { }

        initializeApp() {

            this.platform.ready().then(() => {

	            this.networkProvider.initializeNetworkEvents();

	       		// Offline event
			    this.events.subscribe('network:offline', () => {
			        alert('network:offline ==> '+this.network.type);    
			    });

			    // Online event
			    this.events.subscribe('network:online', () => {
			        alert('network:online ==> '+this.network.type);        
			    });

            });
        }

}

#3

@addwebsolution : but this solution work only the app is loaded time ? I prefer it on all the time when the app is running .

Please advise

Thanks

Anes


#4

@anespa, No it’s work for all time when your network is connected and disconnected


#5

But I got error as

[14:13:58] typescript: src/app/app.component.ts, line: 26
Property ‘platform’ does not exist on type ‘MyApp’.

  L26:              this.platform.ready().then(() => {

Please advise

Thanks
Anes


#6

@anespa Please share your full code here (ts file)
Are u checking it on the root component?


#7

sure

app.component.ts

import { Component } from '@angular/core';
import { Platform, Events } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { Network } from '@ionic-native/network';
import { NetworkProvider } from '../providers/network/network';

import { HomePage } from '../pages/home/home';
@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = HomePage;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();
    });
  }

  initializeApp() {

            this.platform.ready().then(() => {

	            this.networkProvider.initializeNetworkEvents();

	       		// Offline event
			    this.events.subscribe('network:offline', () => {
			        alert('network:offline ==> '+this.network.type);    
			    });

			    // Online event
			    this.events.subscribe('network:online', () => {
			        alert('network:online ==> '+this.network.type);        
			    });

            });
        }
}

  1. app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { IonicStorageModule } from '@ionic/storage';
import { PhotoProvider } from '../providers/photo/photo';
import { NetworkProvider } from '../providers/network/network';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot()
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    PhotoProvider,
    NetworkProvider
  ]
})
export class AppModule {}
  1. Provider (network.ts)
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { AlertController, Events } from 'ionic-angular';
import { Network } from '@ionic-native/network';

/*
  Generated class for the NetworkProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
export enum ConnectionStatusEnum {
    Online,
    Offline
}
@Injectable()
export class NetworkProvider {

  constructor(public http: HttpClient,
              public alertCtrl: AlertController, 
              public network: Network,
              public eventCtrl: Events) {
    console.log('Hello NetworkProvider Provider');
    this.previousStatus = ConnectionStatusEnum.Online;
  }

  public initializeNetworkEvents(): void {
        this.network.onDisconnect().subscribe(() => {
            if (this.previousStatus === ConnectionStatusEnum.Online) {
                this.eventCtrl.publish('network:offline');
            }
            this.previousStatus = ConnectionStatusEnum.Offline;
        });
        this.network.onConnect().subscribe(() => {
            if (this.previousStatus === ConnectionStatusEnum.Offline) {
                this.eventCtrl.publish('network:online');
            }
            this.previousStatus = ConnectionStatusEnum.Online;
        });
    }

}

Please advise


#8

@anespa
Why should u use platform.ready inside constructor?
you already checking it on initializeApp().So try to avoid it from there.
and use
statusBar.styleDefault();
splashScreen.hide();
inside the method initializeApp().Also check network status inside the initializeApp().


#9

I changed app.component.ts as

import { Component } from '@angular/core';
import { Platform, Events } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { Network } from '@ionic-native/network';
import { NetworkProvider } from '../providers/network/network';

import { HomePage } from '../pages/home/home';
@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = HomePage;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
  }

  initializeApp() {

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

	            this.networkProvider.initializeNetworkEvents();

	       		// Offline event
			    this.events.subscribe('network:offline', () => {
			        alert('network:offline ==> '+this.network.type);    
			    });

			    // Online event
			    this.events.subscribe('network:online', () => {
			        alert('network:online ==> '+this.network.type);        
			    });

            });
        }
}

still got error . please advise


#10

@anespa Please let me know the error?


#11

for command

ionic cordova run browser

[15:04:21]  typescript: src/app/app.component.ts, line: 20 
            Property 'platform' does not exist on type 'MyApp'. 

      L20:              this.platform.ready().then(() => {
      L21:                      this.statusBar.styleDefault();

[15:04:21]  typescript: src/app/app.component.ts, line: 21 
            Property 'statusBar' does not exist on type 'MyApp'. 

      L20:  this.platform.ready().then(() => {
      L21:          this.statusBar.styleDefault();
      L22:  this.splashScreen.hide();

[15:04:21]  typescript: src/app/app.component.ts, line: 22 
            Property 'splashScreen' does not exist on type 'MyApp'. 

      L21:                      this.statusBar.styleDefault();
      L22:        		    this.splashScreen.hide();

[15:04:21]  typescript: src/app/app.component.ts, line: 24 
            Property 'networkProvider' does not exist on type 'MyApp'. 

      L24:  	            this.networkProvider.initializeNetworkEvents();

[15:04:21]  typescript: src/app/app.component.ts, line: 27 
            Property 'events' does not exist on type 'MyApp'. 

      L26:   		// Offline event
      L27:  this.events.subscribe('network:offline', () => {
      L28:      alert('network:offline ==> '+this.network.type);    

[15:04:21]  typescript: src/app/app.component.ts, line: 28 
            Property 'network' does not exist on type 'MyApp'. 

      L27:  this.events.subscribe('network:offline', () => {
      L28:      alert('network:offline ==> '+this.network.type);    
      L29:  });

[15:04:21]  typescript: src/app/app.component.ts, line: 32 
            Property 'events' does not exist on type 'MyApp'. 

      L31:  // Online event
      L32:  this.events.subscribe('network:online', () => {
      L33:      alert('network:online ==> '+this.network.type);        

[15:04:21]  typescript: src/app/app.component.ts, line: 33 
            Property 'network' does not exist on type 'MyApp'. 

      L32:  this.events.subscribe('network:online', () => {
      L33:      alert('network:online ==> '+this.network.type);        
      L34:  });

[15:04:21]  typescript: src/providers/network/network.ts, line: 24 
            Property 'previousStatus' does not exist on type 'NetworkProvider'. 

      L23:    console.log('Hello NetworkProvider Provider');
      L24:    this.previousStatus = ConnectionStatusEnum.Online;

[15:04:21]  typescript: src/providers/network/network.ts, line: 29 
            Property 'previousStatus' does not exist on type 'NetworkProvider'. 

      L28:  this.network.onDisconnect().subscribe(() => {
      L29:      if (this.previousStatus === ConnectionStatusEnum.Online) {
      L30:          this.eventCtrl.publish('network:offline');

[15:04:21]  typescript: src/providers/network/network.ts, line: 32 
            Property 'previousStatus' does not exist on type 'NetworkProvider'. 

      L32:      this.previousStatus = ConnectionStatusEnum.Offline;
      L33:  });

[15:04:21]  typescript: src/providers/network/network.ts, line: 35 
            Property 'previousStatus' does not exist on type 'NetworkProvider'. 

      L34:  this.network.onConnect().subscribe(() => {
      L35:      if (this.previousStatus === ConnectionStatusEnum.Offline) {
      L36:          this.eventCtrl.publish('network:online');

[15:04:21]  typescript: src/providers/network/network.ts, line: 38 
            Property 'previousStatus' does not exist on type 'NetworkProvider'. 

      L38:      this.previousStatus = ConnectionStatusEnum.Online;
      L39:  });

Error: Failed to transpile program
    at new BuildError (/home/user/demosetting/node_modules/@ionic/app-scripts/dist/util/errors.js:16:28)
    at /home/user/demosetting/node_modules/@ionic/app-scripts/dist/transpile.js:159:20
    at new Promise (<anonymous>)
    at transpileWorker (/home/user/demosetting/node_modules/@ionic/app-scripts/dist/transpile.js:107:12)
    at Object.transpile (/home/user/demosetting/node_modules/@ionic/app-scripts/dist/transpile.js:64:12)
    at /home/user/demosetting/node_modules/@ionic/app-scripts/dist/build.js:109:82
    at <anonymous>


#13

But Vibin i need this functionality all through pages …


#16

@anespa please call the method initializeApp() inside constructor.This is your error now


#17

Try with:

constructor(private platform: Platform, 
            private statusBar: StatusBar, 
            private splashScreen: SplashScreen) {
    ...
}

#18

Hi, your code is working on me. But, how can I reload the view whenever the network changes?


#19

what if I have wifi connection but no Internet connectivity?
How can I check that???


#20

Do an http request to www.google.com with a timeout


#21

Just a small tip.The network not always could be trusted as stable, so I would do something like this (setTimeout).
So I could make sure that I have a stable network in 3 seconds before I could pass it as online.
Sometimes the app could so slow so the network indicate you’re online but was offline just because the network was so quick to switch to offline. That really mess things up for me once. But this small tip should avoid that.
Network.ts


import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { AlertController, Events } from 'ionic-angular';
import { Network } from '@ionic-native/network';

/*
  Generated class for the NetworkProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
export enum ConnectionStatusEnum {
    Online,
    Offline
}
@Injectable()
export class NetworkProvider {

  constructor(public http: HttpClient,
              public alertCtrl: AlertController, 
              public network: Network,
              public eventCtrl: Events) {
    console.log('Hello NetworkProvider Provider');
    this.previousStatus = ConnectionStatusEnum.Online;
  }

  public initializeNetworkEvents(): void {
        this.network.onDisconnect().subscribe(() => {
            if (this.previousStatus === ConnectionStatusEnum.Online) {
                this.eventCtrl.publish('network:offline');
            }
            this.previousStatus = ConnectionStatusEnum.Offline;
        });
        this.network.onConnect().subscribe(() => {
           setTimeout(() => {
            if (this.previousStatus === ConnectionStatusEnum.Offline) {
                this.eventCtrl.publish('network:online');    
            }
            this.previousStatus = ConnectionStatusEnum.Online;
             }, 3000);
        });
    }

}

#22

I would also like some help here. I followed what you did @addwebsolution but it doesn’t work. The app is not crashing but it does nada when I turn Internetz on and off.

  • I have the ionic cordova network plugin installed
  • Installed Network
  • Imported it to app.module.ts

network.ts

import { Injectable } from '@angular/core';

//Ionic
import { Events } from 'ionic-angular'

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

/*
  This provider checks network connection on the platform and publishes an enum to online or offline state
*/

export enum ConnectionStatus {
  Online,
  Offline
}

@Injectable()
export class NetworkProvider {

  public previousStatus

  constructor(
    public network: Network,
    public events: Events
  ) {
    this.previousStatus = ConnectionStatus.Online;
  }
  
  /* BOOTS a listener on the network */
  public initializeNetworkEvents(): void {

    /* OFFLINE */
    this.network.onDisconnect().subscribe(() => {
      if(this.previousStatus === ConnectionStatus.Online) { 
        this.events.publish('network:offline') 
        this.previousStatus = ConnectionStatus.Offline
      }
    })

    /* ONLINE */
    this.network.onConnect().subscribe(() => {
      if(this.previousStatus === ConnectionStatus.Offline) { 
        this.events.publish('network:online') 
        this.previousStatus = ConnectionStatus.Online
      }
    })

  }

  public getNetworkType(): string {
    return this.network.type
  }



}

app.component.ts

import { Component } from '@angular/core';

//Ionic
import { Platform, Events } from 'ionic-angular';

//Ionic Native
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

//Pages
import { LoginPage } from '../pages/login/login';

//Providers
import { NetworkProvider } from '../providers/network/network'

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = LoginPage;

  constructor( 
    public statusBar: StatusBar, 
    public splashScreen: SplashScreen,
    public platform: Platform,
    public networkStatus: NetworkProvider,
    public events: Events
  ) {

    this.platform.ready().then(() => {
      
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      
      this.initializeApp()
    });
  }

  initializeApp(): void {
    /* Check networkStatus */
    this.networkStatus.initializeNetworkEvents()
    this.events.subscribe('network:offline', () => {
      console.log('network:offline ==> ' + this.networkStatus.getNetworkType())
    })
    this.events.subscribe('network:online', () => {
      console.log('network:online ==> ' + this.networkStatus.getNetworkType())
    }) 

    /* Ionic stuff */
    this.statusBar.styleDefault();
    this.splashScreen.hide();
  }

}



#23

Add

getNetworkStatus(): Observable

:wink:

import { Injectable } from '@angular/core';

import { Events } from 'ionic-angular'

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

import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';

export enum ConnectionStatus {
    Online,
    Offline
}

@Injectable()
export class NetworkService {

    public status: ConnectionStatus;
    private _status: BehaviorSubject<ConnectionStatus> = new BehaviorSubject(null);

    constructor(
        public network: Network,
        public events: Events
    ) {
        this.status = ConnectionStatus.Online;
    }

    public initializeNetworkEvents(): void {

        /* OFFLINE */
        this.network.onDisconnect().subscribe(() => {
            if (this.status === ConnectionStatus.Online) {
                this.setStatus(ConnectionStatus.Offline);
            }
        })

        /* ONLINE */
        this.network.onConnect().subscribe(() => {
            if (this.status === ConnectionStatus.Offline) {
                this.setStatus(ConnectionStatus.Online);
            }
        })

    }

    public getNetworkType(): string {
        return this.network.type
    }

    public getNetworkStatus(): Observable<ConnectionStatus> {
        return this._status.asObservable();
    }
    
    private setStatus(status: ConnectionStatus) {
        this.status = status;
        this._status.next(this.status);
    }
}


Binding to service property needs page refreshing!