Angular2无法在promise中访问“this”

前端之家收集整理的这篇文章主要介绍了Angular2无法在promise中访问“this”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我无法调用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

猜你在找的Angularjs相关文章