本文介绍了Angular2无法在promise中访问"this"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法在ng2-sweetalert2插件的promise中调用函数
I am unable to call a function inside promise of ng2-sweetalert2 plugin
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,但出现了相同的错误
How do I overcome this? I used NgZone but i get the same error
推荐答案
假设您使用的是TypeScript,则可以使用箭头函数表达式,它保留this
的值.
Assuming you're using TypeScript, you could use the arrow function expression, which preserves the value of this
.
swal({...}).then((x) => console.log(this)); // now 'this' is your component
这篇关于Angular2无法在promise中访问"this"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!