首页 > 解决方案 > Ionic 4 ToastController 按钮没有异步功能

问题描述

我需要在我的 ToastController 按钮的处理程序中实现一个函数,该按钮返回一个承诺(这里:this.navCtrl.navigateForward())。

这是我的程序代码:

const toast = await this.toastController.create({
  header: header,
  message: message,
  position: 'bottom',
  animated: true,
  buttons: [
    {
      side: 'start',
      text: 'Action',
      handler: () => {
        this.navCtrl.navigateForward('/destination');
      }
    }
  ]
});
await toast.present();

这给了我信息:Promises must be handled appropriately (no-floating-promises) 我想做的是:

const toast = await this.toastController.create({
  header: header,
  message: message,
  position: 'bottom',
  animated: true,
  buttons: [
    {
      side: 'start',
      text: 'Action',
      handler: async () => {
        await this.navCtrl.navigateForward('/destination');
      }
    }
  ]
});
await toast.present();

但这给了我一个根本没有用的错误消息:

Type '{ side: string; text: string; handler: () => Promise<void>; }' is not assignable to type 'string | ToastButton'.
  Type '{ side: string; text: string; handler: () => Promise<void>; }' is not assignable to type 'ToastButton'.
    Types of property 'side' are incompatible.
      Type 'string' is not assignable to type '"start" | "end"'.

我试图找到解决方案,但现在被卡住了。你有什么想法我错了吗?谢谢!

标签: angulartypescriptionic-frameworkionic4

解决方案


如果您需要等待页面转换,然后在此之后执行某些操作,为什么不使用 .then 方法?

const toast = await this.toastController.create({
  header: header,
  message: message,
  position: 'bottom',
  animated: true,
  buttons: [
    {
      side: 'start',
      text: 'Action',
      handler: () => {
        this.navCtrl.navigateForward('/destination').then(()=>{
            // do something after page transition?
        })
      }
    }
  ]
});
await toast.present();

推荐阅读