Handle network connection

#1

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!

#2

I would use the ionic-native shim.

#3

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.

#4

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

1 Like
#5

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!');   
});
#6

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

#8

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
#9

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

#10

This doesn’t work for me.

navigator.connection is undefined.

#11

Gives me:

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

#12

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.

#13

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