Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'this' is undefined inside function(). angular 2 [duplicate]

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.

like image 575
Joshua Fabillar Avatar asked Jun 22 '17 15:06

Joshua Fabillar


1 Answers

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.

like image 81
scniro Avatar answered Oct 23 '22 13:10

scniro