Angular2无法在promise中访问“this”

时间:2017-03-05 09:27:37

标签: 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);
}

this.removeNote()导致错误。

EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'removeNote' of undefined

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

3 个答案:

答案 0 :(得分:24)

假设您正在使用TypeScript,则可以使用arrow function expression,它会保留this的值。

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

答案 1 :(得分: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);
}

答案 2 :(得分:0)

您也可以使用以下方式:

swal({})
.then(() => { <your angular 2 service call here...>})

以下是工作示例:

customDialog(id,value){
    swal({
      title: 'Are you sure?',
      text: "Message",
      type: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Yes',
      cancelButtonText: 'No',
      confirmButtonClass: 'btn btn-success alertboxmargin',
      cancelButtonClass: 'btn btn-danger alertboxmargin',
      buttonsStyling: false
    }).then(() => {
      this.services.testfunction(table,value,id)
      .subscribe( result => {
        if(result) {
          if(value) {
            swal('Message!','Message.','success')
          }
          else {
            swal('Message!','Message.','success')
          }          
        }
        else {
          swal('Error!','Try again later.','error')
        }        
      });
    },
      function (dismiss) {
      // dismiss can be 'cancel', 'overlay',
      // 'close', and 'timer'
      if (dismiss === 'cancel') {
        swal('Cancelled','No action performed!','error')
      }
    })//then closing
} // Dialog Closing