No puedo llamar a una función dentro de la promesa del complemento 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()
causa un error.
EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'removeNote' of undefined
¿Cómo supero esto? Usé NgZone pero recibo el mismo error
Suponiendo que está usando TypeScript, podría usar laexpresión de función de flecha , que conserva el valor de this
.
swal({...}).then((x) => console.log(this)); // now 'this' is your component
esto es porque this
se refiere a la promesa misma. hacer esto :
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); }
También puede usar la siguiente manera:
swal({}) .then(() => { <your angular 2 service call here...>})
El siguiente es el ejemplo de trabajo:
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