Cannot access current network state. Type is always 'null'

I’m using the ionic-native/network at startup in my app, and I want to check the initial network status by running network.type. The problem is that network.type always returns null or it is simply empty.

The network plugin works perfectly fine when using network.onConnect() and network.onDisconnect(), where I can handle a change in the internet connection, but I can’t access the current network state after app launch.

Here is my home page:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Network } from '@ionic-native/network';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController, private network : Network) {
    console.log("Network type: " + network.type)
  }
}

And the console log:

Network type: null

Any ideas how to access the current network state without waiting for a certain change to happen?

Thanks!

Hi, @perzach

Can you try

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

  setTimeout(() => {
    if (this.network.type === 'wifi') {
    }
  }, 3000);
});

And check in Device.

Link : https://ionicframework.com/docs/native/network/

Thanks

Thanks for the reply, @addwebsolution. Unfortunately I have tried using the subscription to onConnect() without any luck. What happens is that it will detect when there is a change to the network connection, but it will not be triggered if the device is offline when I launch the app. So if I am offline and launch the app - and then try to do something like ‘download information from the web’ (which should be prevented by the app to avoid crashing) then the app will still try to perform the action since it does not know that it is offline.

The only way I have been able to register that the device is offline is if it changes from online to offline.

What happens if you wrap the attempt to check network state in a Platform.ready().then() block?

It still returns as null :confused:

Fixed the problem by performing an internet request instead of asking ionic for the connection type. It’s similar to the solution found in this post: Checking Internet connection - #6 by rapropos

Creds to @rapropos for this:

Establish a /heartbeat endpoint or something in your backend that just always returns 200 OK.

this._http.get('/heartbeat').subscribe(() => {
    // yep, good to go
  }, (err) => {
    // ruh roh
  });