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!",
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()
cause error.
EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'removeNote' of undefined
How do I overcome this? I used NgZone but i get the same error
How To Create Promises in Angular? To create a promise in Angular we just need to use 'new Promise(function)' syntax. The promise constructor takes function as a parameter and that inner function takes resolve and reject as a params.
A promise is a placeholder for a future value. It serves the same function as callbacks but has a nicer syntax and makes it easier to handle errors.
A promise is a JavaScript/TypeScript object that may produce a value at some point in time. A promise may be in one of 4 possible states: fulfilled, rejected, pending or settled. A promise can be: fulfilled - The action relating to the promise succeeded.
Promises deal with one asynchronous event at a time, while observables handle a sequence of asynchronous events over a period of time. Emit multiple values over a period of time. Emit a single value at a time. Are lazy: they're not executed until we subscribe to them using the subscribe() method.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With