Angular2 cannot access 'this' inside a promise

前端 未结 3 1594
伪装坚强ぢ
伪装坚强ぢ 2021-01-05 21:27

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!\"         


        
相关标签:
3条回答
  • 2021-01-05 21:40

    You can use like following manner also:

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

    Following is the working example:

    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
    
    0 讨论(0)
  • 2021-01-05 21:49

    this is because this refers to the promise itself. do 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);
    }
    
    0 讨论(0)
  • 2021-01-05 21:51

    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
    
    0 讨论(0)
提交回复
热议问题