I've written a provider to help track network connectivity using the Native Network plugin:
import { Injectable } from '@angular/core';
import { Network } from '@ionic-native/network';
import { Platform } from 'ionic-angular';
@Injectable()
export class Connectivity {
public online: boolean = false;
constructor(private network: Network) {
this.network.onDisconnect().subscribe(() => {
console.log('Network offline');
this.online = false;
});
this.network.onConnect().subscribe(() => {
this.online = true;
console.log('Network online');
});
});
}
}
I've installed the relevent plugins (package.json
):
"cordova-plugin-network-information": "^2.0.1",
...
"@ionic-native/network": "^4.7.0",
And I've included my provider in my app.module.ts
:
providers: [
Network,
StatusBar,
SplashScreen,
Connectivity,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
Yet, when I run the app in the browser, neither of the observables fire. If I try print: console.log(this.network.type)
in the provider constructor, it just prints null
.
The answer here is that the native network plugin doesn't work in the browser. Even though it has "browser" listed as a supported platform:
It is referring to the Cordova Browser which is different to a web browser. I found this out after discussion on the Ionic Slack channel.
You need to instead write a Provider that:
For others with the same problem: