How to call method i sweetalert 2

老子叫甜甜 提交于 2019-12-24 08:16:24

问题


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?


回答1:


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

})



回答2:


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


来源:https://stackoverflow.com/questions/45758619/how-to-call-method-i-sweetalert-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!