Search code examples
angularcordova-pluginsionic2

Verify changes in internet connection ionic2


I see this tutorial to determine network availability in ionic2: https://www.thepolyglotdeveloper.com/2016/01/determine-network-availability-in-an-ionic-2-mobile-app/

But my question is: there's a way to show the dialog "automatically" when the network status change (without using Observable.period())?

Thanks!


Solution

  • 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);
        });
      }
    }