我无法调用ng2-sweetalert2插件的承诺内的函数
swal({ title: 'Are you sure?',text: "You won't be able to revert this!",type: 'warning',showCancelButton: true,confirmButtonText: 'Yes,delete it!' }).then(function(x) { this.removeNote(key); swal( 'Deleted!','Your file has been deleted.','success' ); },function(e){ console.log('Cancelled'); }); removeNote(key){ this.todo.remove(key); this.afService.closeNote(key); }
this.removeNote()导致错误.
EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'removeNote' of undefined
我该如何克服这个问题?我使用了NgZone,但我得到了同样的错误
解决方法
假设你正在使用TypeScript,你可以使用
arrow function expression,它保留了它的值.
swal({...}).then((x) => console.log(this)); // now 'this' is your component