Check connection if offline doesn't show Toast

#1

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,

#2

Does adding an await keyword to your method call help?

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

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

#4

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:

#5

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:

#6

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

#7

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

#8

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

#9

use the navigator. It Works perfectly…

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

} else{
  this.isconnected=false
}
#10

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.