Ionic toast can't be dismissed manually


#1

I am working on an ionic2 project and trying to show connection status message in the app. Here is my code:

import { ToastController, Toast  } from 'ionic-angular';
connectedToast: Toast; disconnectedToast: Toast;

this.connectedToast = this.toast.create({
        message: `You are now ${networkstatus.connectType} via ${networkstatus.networkType}`,
        position: 'bottom',
        cssClass: 'toast-connected',
        duration: 3000
    });

    this.disconnectedToast = this.toast.create({
        message: `This function is not available because you are ${networkstatus.connectType}`,
        position: 'bottom',
        cssClass: 'toast-disconnected'
    });

    if(networkstatus.isOnline) {              
        if(this.disconnectedToast != null)                 
            this.disconnectedToast.dismiss();

        this.connectedToast.present();
    }

    if(networkstatus.isOffline) this.disconnectedToast.present();

What I wanted to achieve is: if offline, toast msg will stay there until it is online. But for online message, it will only display for 3 seconds. Everything is working fine except when it is online and after online message is displayed, the offline toast msg stays there and didn’t disappear even though I called dismiss(). Did I miss anything here?

my environment is: “ionic-angular”: “3.3.0”, “ionic”: “3.6.0”, “typescript”: “2.3.3”

Any help will be appreciated!


#2

I never assign toasts to object properties, as it facilitates reuse and double-dispose bugs and makes code harder to read, because ownership of the toast is spread out across multiple places. Perhaps restructuring your code to use lexically scoped variables instead of object properties might make the problem either go away or give you some more insight as to what is happening.


#3

Thanks for your reply. Can you give me an example what you mean by


#4

In short, instead of defining your toast as class variable instead define inside of your function.

E.g.

public showAwesomeToast() {
  let toast = this.toast.create({
    message: "Radical!"
  )};

  toast.present();
}

#5

Thanks for the answer.


#6

Simply create separate function and pass message to it and show message.