Ionic: 如何避免多个toast通知叠加显示?

11

我得到了以下Ionic代码片段,用于在工业应用程序中显示警报/错误:

showError(message: string) {
  let toast = this.toastController.create({
      message: message,
      position: 'top',
      duration: 5000,
      cssClass: 'danger',
      showCloseButton: true
  });
  toast.present();
}

每次检测到连接问题,该应用程序都会触发错误消息,并且大约在5秒定时器上运行。如果更改此代码的时间,对此方法进行多次调用将导致2个或更多错误消息叠加显示。我可以以某种方式检测到烤面包已经显示吗?即使如此,也不需要5000毫秒计时器,当重新建立连接时,我只需删除错误消息即可。

谢谢,Florian

8个回答

17

您可以在函数外部将Toast对象存储在变量中,并在显示下一个 Toast 之前调用 dismiss() 方法:

Ionic 4

import { ToastController } from '@ionic/angular';


toast: HTMLIonToastElement;    

showError(message: string) {
    try {
        this.toast.dismiss();
    } catch(e) {}

    this.toast = this.toastController.create({
        message: message,
        position: 'top',
        duration: 5000,
        color: 'danger',
        showCloseButton: true
    });
    toast.present();
}

Ionic 3

->

Ionic 3

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


toast: Toast;    

showError(message: string) {
    try {
        this.toast.dismiss();
    } catch(e) {}

    this.toast = this.toastController.create({
        message: message,
        position: 'top',
        duration: 5000,
        cssClass: 'danger',
        showCloseButton: true
    });
    toast.present();
}

嗨,需要澄清一下。上面的代码并不能防止重复的提示,对吧?它只是关闭当前的提示,然后再创建一个新的。我说得对吗? - Arj 1411
我不是100%确定,但我认为当你调用dismiss()时,toast也会从DOM中移除。 - jbgt
如果 Toast 已经自动消失,那么调用 dismiss() 方法将会导致错误。 - Amr Eladawy
这就是为什么你可以将其包装在 try / catch 中,在调用 dismiss() 时捕获错误的原因。 - jbgt
防止Ionic2中重复出现的Toast消息 - user542319

4
这是我的解决方案 :-)
// ToastService.ts
import { Injectable } from '@angular/core';
import { ToastController, Toast } from 'ionic-angular';

@Injectable()
export class ToastService {

  private toasts: Toast[] = [];

  constructor(private toastCtrl: ToastController) {}

  push(msg) {
    let toast = this.toastCtrl.create({
      message: msg,
      duration: 1500,
      position: 'bottom'
    });

    toast.onDidDismiss(() => {
      this.toasts.shift()
      if (this.toasts.length > 0) {
        this.show()
      }
    })

    this.toasts.push(toast)

    if (this.toasts.length === 1) {
      this.show()
    }
  }

  show() {
    this.toasts[0].present();
  }

}

1

我在使用8月20日之前的答案时遇到了麻烦,弹出窗口仍然会出现多次。通过检查并设置布尔值来判断是否继续进行,可以简单地解决问题。将其直接设置为true,就不会再运行多次了。

isToastPresent = false;

async presentToast(message: string, color?: Colors, header?: string): Promise<void> {
  if (!this.isToastPresent) {
    this.isToastPresent = true;

    const toast = await this.toastController.create({
      message: message,
      header: header || undefined,
      duration: 3500,
      position: 'top',
      color: color || Colors.dark,
    });

    toast.present();

    toast.onDidDismiss().then(() => (this.isToastPresent = false));
  }
}

1

您可以检查是否已经存在一个 toast,如果没有则创建新的。

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


toast: Toast;    
isToastPresent:boolean=false;

show(){

this.isToastPresent?'':this.showError('No network');

}

showError(message: string) {

    this.toast = this.toastController.create({
        message: message,
        duration: 3000,
        cssClass: 'danger',
        showCloseButton: true
    });
    toast.present();
     this.isToastPresent=true;

    this.toast.onDidDismiss(() => {
      this.isToastPresent=false;
      console.log('Dismissed toast');
    });

}

0

显示一系列持续时间的吐司消息。

Ionic 6

  toastCtrl(color,msg,duration?) {
    const toast = {
      message: msg,
      color: color,
      duration: duration || 3000
    };
    this.toasts.push(toast)
    const timeout = (this.toasts.length - 1) * toast.duration
    this.show(timeout);
  }
  show(timeout) {
    setTimeout(async () => {
      const toast = await this.toastController.create(this.toasts[0]);
      await toast.present();
      this.toasts.splice(0, 1);
    }, timeout > 0 ? timeout + 800 : 0);

  }

0
import { ToastController, Toast } from 'ionic-angular';

.........

private toast: Toast;

.........

    export Class ToastService{

.........

         showToastMessage(messageData) {

            if (this.toast) this.toast.dismiss();

            this.toast = this.toastCtrl.create({
              message: messageData,
              cssClass: "error-toast-cls",
              dismissOnPageChange: true,
              showCloseButton: true,
              closeButtonText: "Enable"
            });
            this.toast.onDidDismiss((data, role) => {
              if (role == 'close') {
                this.diagnostic.switchToWirelessSettings()
              }
            })
            await this.toast.present()  
     }

    }

0

Ionic 4 Toast UI 组件中

使用以下代码仅显示Ionic 4 Toast一次

// Call this method  
showOnceToast(){
  this.toastController.dismiss().then((obj)=>{
  }).catch(()=>{
  }).finally(()=>{
    this.manageToast();
  });
}

manageToast() {
  this.toastInstance = this.toastController.create({
    message: 'Your settings have been saved.',
    duration: 2000,
    animated: true,
    showCloseButton: true,
    closeButtonText: "OK",
    cssClass: "my-custom-class",
    position: "middle"
  }).then((obj) => {
    obj.present();
  });
}

enter image description here

源链接:http://www.freakyjolly.com/ionic-4-adding-toasts-in-ionic-4-application-using-ui-components-with-plugins/


0

我用这种方式解决了

private mensajeErrorEnvioTramiteActivo = false;
  mensajeErrorEnvioTramite() {
    if (!this.mensajeErrorEnvioTramiteActivo) {
      this.mensajeErrorEnvioTramiteActivo = true;
      let toast = this.toastCtrl.create({
        message: "No se pudo enviar los tramites formalizados, por favor reenvielos",
        position: 'top',
        showCloseButton: true,
        closeButtonText: 'REENVIAR',
      });

      toast.onDidDismiss(() => {
        this.reenvioKits.reenviarTramites();
        this.mensajeErrorEnvioTramiteActivo = false;
      });
      toast.present();
    }

  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接