【问题标题】:How to call method i sweetalert 2如何调用方法 i sweetalert 2
【发布时间】:2017-08-18 14:04:28
【问题描述】:

在我的 angular 4 项目中,我使用的是 sweetalert 2 的主题,我想在用户单击确认按钮时调用我的方法,但似乎我无法在 then 函数中调用任何方法

swal({
  title: 'Are you sure?',
  text: "You won't be able to revert this!",
  type: 'warning',
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Yes, delete it!'
}).then(function () {

  // I want to call my method here but I can't do this.myMethod()

})

我知道这不是 angular sweetalert,但是否有可能在不改变的情况下使其工作?

【问题讨论】:

    标签: angular sweetalert sweetalert2


    【解决方案1】:

    使用箭头函数符号() =>。当您使用function 关键字时,您将失去对this 的访问权限。将您的代码更改为以下代码:

    swal({
      title: 'Are you sure?',
      text: "You won't be able to revert this!",
      type: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Yes, delete it!'
    }).then(()=> {
    
      this.myMethod(); // this should execute now
    
    })
    

    【讨论】:

    • 很高兴帮助@m007 :)
    【解决方案2】:

    正确答案对我也有帮助,尽管我必须解决如何捕获“Uncaught in promise”错误。如果有人发现使用取消按钮有帮助,我想我会在此处添加它以完成。

    swal({
       //code         
    }).then(()=> {
       //code
    },(error: any) => console.log(error));
    

    【讨论】:

      猜你喜欢
      • 2017-04-28
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-10
      • 2015-08-09
      • 1970-01-01
      相关资源
      最近更新 更多