1

在我的 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()

})

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

4

2 回答 2

7

使用箭头函数表示法() =>。当您使用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

})
于 2017-08-18T14:10:47.147 回答
1

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

swal({
   //code         
}).then(()=> {
   //code
},(error: any) => console.log(error));
于 2018-11-15T07:24:40.773 回答