Ionic: check if the device has a connection

Viewed 477

i want to execute an specific function when the device has an Internet connection.

I try this:

checkConnection(API){
  this.network.onConnect().subscribe(() => {
    this.changeAPI(API);
  });
  this.network.onDisconnect().subscribe(() =>{
    let loading = this.loadingCtrl.create({
      content: 'No Connection'
    });

    loading.present();

    setTimeout(() => {
      loading.dismiss();
    }, 1500);
  });
}

But its doesnt work, so how i can check the connection?

1 Answers

I recommend using an observable for this particular feature. Also, implementing a service will allow you to check the connection throughout the whole application.

//.ts

import { Injectable } from '@angular/core';
import { Network } from '@ionic-native/network';
import { Subscription } from 'rxjs/Subscription';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/interval';
 
Injectable()
export class DataService {
      connected: Subscription;
      disconnected: Subscription;
      public networkType:any;
      public online:any;
      constructor(  public network: Network){

          //May have to unsubscribe from Observable
        this.checkConnection = Observable.interval(250 * 60).subscribe(x => {
      //Check for connection every 15 seconds
          this.connected;
          this.disconnected;
          this.networkType = this.network.type;
          this.connected = this.network.onConnect().subscribe(data =>{
               this.online = data.type;
             }, error => console.error(error));

          this.network.onDisconnect().subscribe(data =>{
                this.online = data.type;
             },);
            }, error => console.error(error));
          }
        removeConnections(){
      this.checkConnection.unsubscribe();
      }
    }

show in another page

import { Component } from '@angular/core';
import { IonicPage,NavParams} from 'ionic-angular';
import { DataService } from '../../services/dataservice';//service

@IonicPage()
@Component({
  selector: 'page-support',
  templateUrl: 'support.html',
})
export class SupportPage {
    constructor(private service: DataService){
    }
   }
//.html
<ion-header>
  <ion-navbar>
    <ion-title>Support</ion-title>
  </ion-navbar>
</ion-header>


<ion-content padding>
  <ion-grid>
     <ion-row>
        <ion-col>
          <h1>Connection: {{this.reap.networkType}}</h1>
        </ion-col>
      </ion-row>
  </ion-grid>
</ion-content>

The observable will constantly check your connection until you unsubscribe from it. So it will change in the html code as well.

Related