This question already has answers here:
How to access the correct `this` inside a callback?
(11 answers)
Closed 2 years ago.
So I am using a uikit confirmation modal in my app. My problem is, when I am going to click the <button>
for confirmation. the this
inside function is undefined
. here's my code...
declare var UIkit:any;
deleteData(dataArr): void {
UIkit.modal.confirm('Are you sure you want to delete this?', function() {
console.log(dataArr);
console.log(this);
//use service here...
UIkit.modal.alert('Confirmed!');
});
}
Inside that function I wish to use service for http request but I am having a problem on the this
. I am using Angular 2.x.
Use an arrow function...
declare var UIkit:any;
deleteData(dataArr): void {
UIkit.modal.confirm('Are you sure you want to delete this?', () => {
console.log(this);
// [...]
});
}
Check out MDN: Arrow functions for details on the matter.
An arrow function does not create its own this context, so this
has
its original meaning from the enclosing context.
'this' is not passed to your function scope, try
declare var UIkit:any;
deleteData(dataArr): void {
var that = this;
UIkit.modal.confirm('Are you sure you want to delete this?', function(){
console.log(dataArr);
console.log(that);
//use service here...
UIkit.modal.alert('Confirmed!');
});
}