Handle network connection

Hello everyboy,

I need to know if there is internet connection (in general, any type) and it’s not working.

If i do:

if (Network.connection) {
   // yes
} else {
  // no
}

The docs says to use Network.type but the editor says this property doesn’t exists, and with Network.connection (whose description says it returns a string with the internet type) always returns undefined.

Thank’s in advance!

I would use the ionic-native shim.

Yes, this is that I’m trying to use, but it’s not working. And my editor says “Network.type” does not exist in Network. And now, it is Network.connection.

If I find a solution I will paste it here.

Why aren’t you using the various Observables, then? They seem much more friendly.

1 Like

Because they only works when a change in the network is detected. A connection or disconnection. I need to know in advance whether or not there is a connection, and these observables do not yield any results when I open the app, unless once the app is open, connect and disconnect the network:

let disconnectSubscription = Network.onDisconnect().subscribe(() => {
    console.log('network was disconnected :-(');
});

let connectSubscription = Network.onConnect().subscribe(() => {
    console.log('network connected!');   
});

Well, your editor seems broken to me. Mine does not complain about Network.type, and neither does the build process.

I solved it:

import { Network } from 'ionic-native';

declare var navigator: any;
declare var Connection: any;


@Component
.
.
.


public setOnlineStatus(): void {

    this.platform.ready().then(() => {
        this.checkConnection();
    });
}

public checkConnection(): void {

    var networkState = navigator.connection.type;

    if (networkState === Connection.NONE) {
        this.isOnline = false;
    } else {
        this.isOnline = true;
    }
}
1 Like

hi colo j ai essaye mais je trouve des erour sur isoline

This doesn’t work for me.

navigator.connection is undefined.

Gives me:

[ts] Property ‘onConnect’ does not exist on type ‘Network’.
any

Judging from that capital ‘N’, I’m guessing you’re using <3 static syntax. In version 3, that all switched to using injectables. Inject a Network in your constructor and call things on it, not on the class.

You need install the plugin:

ionic cordova plugin add cordova-plugin-network-information
npm install --save @ionic-native/network

and you could acces to the navigator.network.connection.type