i am working with ionic 2 RC1 and using sublime as text editor. i need to check if the network connection is connected or not. so for this purpose i am using ionic native Network for this purpose. but i am facing problem with the Network.onDisconnect()
Observable. I have edited initializeApp()
method in which i check for network connection and show alert if connection got disconnected. the I have the following code written in app.component.ts
showAlert(title, msg) {
let alert = this.alertCtrl.create({
title: title,
subTitle: msg,
buttons: ['OK']
});
alert.present();
}
initializeApp() {
this.platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
let disconnectSubscription = Network.onDisconnect().subscribe(() => {
this.showAlert("Error", "No internet connection");
});
StatusBar.styleDefault();
});
}
The problem i am facing is that alert is shown twice if application get disconnected from internet. I have found similar issue in this post but it got unanswered. Any help on this regard will be much appreciated. Thanks in advance !
i think you should use below code to avoid that problem.
I have solved this issue. The real problem that people are having is that in a lot of cases multiple instances of Ionic pages are created. So if you register an event receiver on a page and then start navigating back and forth through the App, the event receiver will be registered multiple times. The solution is to add the event receiver in app.component.ts 's intializeApp method, like so:
Both log messages will only be triggered once when you go online/offline respectively no matter how much you navigate within the App.
In order to avoid that, you can filter the events, and just do something when the state changes from online to offline, or from offline to online (and not every time the event is being fired by the plugin). So basically you can create a service to handle all this logic like this:
So our custom events (
network:offline
andnetwork:online
) will only be fired when the connection truly changes (fixing the scenario when multiple online or offline events are fired by the plugin when the connection state hasn't changed at all).Then, in your
app.component
file you just need to subscribe to our custom events:Your real problem is, that you don't use an binded constructor in your actual class! If you want to call that for example in app.component.ts then just add the parameter to your
and use is besides Network directly! so call: this.network.... then the best would be to control that with a static variable like:
after you wrote your OnConnect statement set the checkedState to true and catch that with an if statement on both: OnDisconnect and OnConnect and you should only get once a message. By the way: i had that behavior also with eventsCtrl and I don't know If Ionic is handling these things better with other contro mechanism's.
Greets Rebar