How to call method i sweetalert 2

2019-07-25 11:43发布

In my angular 4 project I am using a theme with sweetalert 2, I want to call my method when user click on the confirm button, but it seems that I can't call any method inside then function

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()

})

I know It's not the angular sweetalert but is it possible to make it work without change?

2条回答
Lonely孤独者°
2楼-- · 2019-07-25 12:18

Use the arrow function notation () =>. When you use the function keyword, you loose the access to this. Change your code to the below instead:

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

})
查看更多
你好瞎i
3楼-- · 2019-07-25 12:22

The correct answer helped me too, although I had to solve how to catch the "Uncaught in promise" error. I thought I'd just add it here for completion if anyone found it helpful using the cancelButton.

swal({
   //code         
}).then(()=> {
   //code
},(error: any) => console.log(error));
查看更多
登录 后发表回答