Network detection

hello,

i follow this tuto https://youtu.be/CFoG0xkgVlE from Simon Grimm to check connectivity.

Two remarks :

  • displaying status network works fine only if i navigate and come back to the page.

  • toast message seems to works only with the last value

I really love to not have to navigate and come back to display the network status.

here is “my” code :

network service :

import { Injectable } from '@angular/core';
import { Network } from '@ionic-native/network/ngx';
import { BehaviorSubject, Observable,of} from 'rxjs';
import { ToastController, Platform } from '@ionic/angular';


export enum ConnectionStatus {
  Online,
  Offline
}

@Injectable({
  providedIn: 'root'
})
export class Network2Service {

  public status: BehaviorSubject<ConnectionStatus> = new BehaviorSubject(ConnectionStatus.Offline);

  constructor( private toastController: ToastController, private plt: Platform) { 
    this.plt.ready().then( ()=>{
      this.initializeNetworkEvents();
      let status = this.network.type !== 'none' ? ConnectionStatus.Online : ConnectionStatus.Offline;
      this.status.next(status);
    });
  }

  public initializeNetworkEvents(){
    console.log('initialize network events');
    
    this.network.onDisconnect().subscribe( ()=>{
      if(this.status.getValue() === ConnectionStatus.Offline){
        console.log('We are Offline');
        this.updateNetworkStatus(ConnectionStatus.Offline);
      }
    });

    this.network.onConnect().subscribe( ()=>{
      if(this.status.getValue() === ConnectionStatus.Online){
        console.log('We are Online');
        this.updateNetworkStatus(ConnectionStatus.Online);
      }
    });

  }
  
  private async updateNetworkStatus(status: ConnectionStatus) {
    this.status.next(status);

    let connection = status == ConnectionStatus.Offline ? 'Offline' : 'Online';
    let toast = this.toastController.create({
      message: `You are now ${connection}`,
      duration: 3000,
      position: 'middle'
    });
    toast.then(toast => toast.present());
  }

  public onNetworkChange(): Observable<ConnectionStatus> {
   return this.status.asObservable();
  }

  public getCurrentNetworkStatus(): ConnectionStatus {
    return this.status.getValue();
  }

}

component :

...
public status:Observable<ConnectionStatus>;
....

ngOnInit() {
 this.network2Service.onNetworkChange().subscribe( status=>this.status=of(status) );
}

view

...
    <ion-grid>
        <ion-row><ion-col>Status</ion-col></ion-row>
        <ion-row><ion-col>{{ status | async }}</ion-col></ion-row>
    </ion-grid>
...

i’ll try w/out async too: {{status}} , same result.

So how can i display " status" network in live (without navigate and come back) ?

Thank you for help
n

I still looking for a solution,
my readings take me at this question : what is the version of network should i use ?

here is what i have actually :

@ionic-native/core”: “5.0.0-beta.21”,
@ionic-native/network”: “^5.5.1”,

is this version works ? is there someone working with it ?

thank you,
N

basic question : is it possible to hide/show button binded to an observable (based on network detection) ?
the solution i have works on navigator (testing) but not on device … still stucked :frowning:

thank you,
n

i reply to myself : yes it is possible to hide/show anything based on observable.

i finally change my code (Simon tuto’s above) with this and its work really fine, both on browser and devices !

so i share :slight_smile:

in service :

import { Network } from '@ionic-native/network/ngx'; (5.6.0 version)

constructor(public network: Network, public platform: Platform) { 
        this.online$ = Observable.create(observer => {
          observer.next(true);
      }).pipe(mapTo(true));
    
      if (this.platform.is('cordova')) {
          // on Device
          this.online$ = merge(
              this.network.onConnect().pipe(mapTo(true)),
              this.network.onDisconnect().pipe(mapTo(false))
          );
      } else {
          // on Browser
          this.online$ = merge(
              of(navigator.onLine),
              fromEvent(window, 'online').pipe(mapTo(true)),
              fromEvent(window, 'offline').pipe(mapTo(false))
          );
      }
      
  }


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

public getNetworkStatus(): Observable<boolean> {
    return this.online$;
}

in component

....
ngOnInit {
...
this.networkSubscriber();
}

 networkSubscriber(): void {
    this.networkService
        .getNetworkStatus()
        .pipe(debounceTime(400))
        .subscribe((connected: boolean) => {
            this.isConnected = connected;
            console.log('isConnected = ', this.isConnected);
            this.handleNotConnected(connected);
        });
  }

handleNotConnected(status){

  if(status === true){
        this.isConnected=true;
        console.log('You are now Online');
        this.presentToast('You are now Online');
      }else{
        this.isConnected=false;
        console.log('You are now Offline');
        this.presentToast('You are now Offline');
      }
  
  }

html

<div *ngIf="isConnected  === true && allCampagneCompleted && campagnes.length >0">
      <ion-grid>
        <ion-row>
          <ion-col text-center>
            <ion-button  (click)="sync()">Push Data</ion-button>
          </ion-col>
        </ion-row>
        
      </ion-grid>
    </div>

A complete working code, for me same logic of Simon’s tutorial , i dont understand why this is working better than the other,
so if someone have idea, tell me !

thank you,
n

Hi, I use this default approach provided by JavaScript:

if (navigator.onLine) {
 console.log('Internet is connected');
} else {
 console.log('No Internet Connection found!');
}

But it’s not completely perfect way of detecting internet. You can learn more about it in W3School. Here is the quick link:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_nav_online

hmm … does the network plugin have a web implementation? When I was working on it, a few months ago, it didn’t have one