Check connection if offline doesn't show Toast

Capture1

I want to show toast alert when disconnected but it just showed the alert above, please tell me how to fix it. Thanks guys,

Does adding an await keyword to your method call help?

this.event.subscribe('network:offline', async () => {
...
...
await this.networkAlrert();

Tks u, I tried it but it still doesn’t work. Do you have any idea else ?

Hello,
Import the Network in app.module.ts file

import { Network } from '@ionic-native/network/ngx';

add the network in provider

providers: [ Network ]

now open an app.component.ts file and import the Network and ToastController

import { Network } from '@ionic-native/network/ngx';
import { ToastController } from '@ionic/angular';

constructor(private network: Network, public toastController: ToastController) { }

  initializeApp() {
  this.platform.ready().then(() => {
    // watch network for a disconnection
    let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
      alert('network was disconnected :-(');
       const toast = await this.toastController.create({
        message: 'You are appear to be offline. Please try again!.',
        showCloseButton: true
      });
      toast.present();
    });
    // watch network for a connection
    let connectSubscription = this.network.onConnect().subscribe(() => {
      alert('network connected!');
    });
    this.statusBar.styleDefault();
    this.splashScreen.hide();
  });
}

OR

you just want show alert, try to put your toast code after this.splash = true;.
Hope that help you :slight_smile:

2 Likes

Tks u but it still doesn’t work. It just show the alert ‘network was disconnected :-(’
I’ve tried Ionic Native Dialogs and Toast and both worked. But neither ToastController nor AlertController work as it expected, I don’t know why :roll_eyes:

Hello, just use my code and it’s working perfect in my app and don’t use plugin for toast. use this component for toast

It worked well in Android but just worked only at first time with onDisconnect on IOS (tested with Simulator). Maybe a problem with IOS ?

Should work without issues. By the way, why do you need await in await toast.present(); ?

use the navigator. It Works perfectly…

if(navigator.onLine)
{
this.isconnected=true

} else{
  this.isconnected=false
}

I’m having a similar issues with Toasts in Ionic 4+. I found this bug report that describes the issue in more detail. Apparently, the ToastController (and other controllers) can fail when the device is offline due to lazy loading.

Sadly, I don’t have a workaround for using toasts when offline yet.

if (this.network.type == 'none' ) {
     this.toastCtrl.create ({
     message: 'Check your Network connection.Please check your wifi or mobile data',
     duration: 3000,
    }).present();
    } else {
   console.log('Internet Connection is live')
  }