Angular2无法在promise中访问"this"

Ash*_*eer 5 angular

我无法调用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);
}
Run Code Online (Sandbox Code Playgroud)

this.removeNote() 导致错误.

EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'removeNote' of undefined
Run Code Online (Sandbox Code Playgroud)

我该如何克服这个问题?我使用了NgZone,但我得到了同样的错误

Bro*_*row 27

假设你正在使用TypeScript,你可以使用箭头函数表达式,它保留了值this.

swal({...}).then((x) => console.log(this)); // now 'this' is your component
Run Code Online (Sandbox Code Playgroud)


Bou*_*ine 8

这是因为this指的是承诺本身.做这个 :

let self = this;
   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) {
    self.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);
}
Run Code Online (Sandbox Code Playgroud)