how to detect internet connectivity in ionic 5

Viewed 10354

I am working on an android app and I want to detect when my internet connection is available and not with this ionic plugin, cordova-plugin-network-informationbut when i ran this command ionic cordova plugin add cordova-plugin-network-information in my command prompt i got this error

Unexpected token   in JSON at position 0
[ERROR] An error occurred while running subprocess cordova.    
        cordova.cmd plugin add cordova-plugin-network-information exited with exit code 1.    
        Re-running this command with the --verbose flag may provide more information.

even when i added the --verbose to it, i still got the same error i am using windows 10, please how can i resolve this

2 Answers

The plugin gives you a lot of additional information about the nature of the connection, the strength of the signal, etc. But depending on your use case you may just try adding simple online/offline detection functionality using Web APIs:

connectivity.provider.ts:

import { Injectable } from '@angular/core';
import { Observable, fromEvent, merge, of} from 'rxjs';
import { map } from 'rxjs/operators';

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

  public appIsOnline$: Observable<boolean>;

  constructor() {

    this.initConnectivityMonitoring();

  }

  private initConnectivityMonitoring() {

    if (!window || !navigator || !('onLine' in navigator)) return;

    this.appIsOnline$ = merge(
      of(null),
      fromEvent(window, 'online'),
      fromEvent(window, 'offline')
    ).pipe(map(() => navigator.onLine))

  }

}

This way you have this code working across both hybrid builds and PWA and also avoid additional binary functionality concerns.

This provider can be imported in a component, injected via the constructor and then subscribed to the stream of boolean events:

this.connectivityProvider.appIsOnline$.subscribe(online => {

    console.log(online)

    if (online) {

        // call functions or methods that need to execute when app goes online (such as sync() etc)

    } else {

        // call functions on network offline, such as firebase.goOffline()

    }

})

Here is stackblitz: https://stackblitz.com/edit/ionic-angular-v5-z34sqf

So if you use Chrome's dev tools performance tab and simulate online/offline it works pretty reliably: enter image description here

I would update Ionic: npm update -g ionic

I still prefer to:

npm uninstall -g ionic 
npm install -g ionic

You can also generate a new project and install the: cordova-plugin-network-information and see if it runs without any issue, then you can compare the files to see if there is something different: package.json, tsconfig.json, etc

OR, you you can install Capacitor version of the plugin, it's possible to use both Cordova and Ionic Native plugins altogether:

npm install cordova-plugin-network-information
npm install @ionic-native/network
ionic cap sync
Related