Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a class method inside a promise in Angular 2?

If I have an Angular 2 component and I get data from a service that returns an async promise or observable how can I then call a method in the component to display that data?

@Component({
  moduleId: module.id,
  selector: 'charts',
  templateUrl: 'charts.component.html',
  providers: [DataService]
})
export class ChartsComponent implements OnInit {

  constructor(private dataService:DataService)

  ngOnInit() {
    this.getData();
  }

  getData(){
    this.dataService.getData().then(function (data) {
      this.drawChart(data);
    });
  }

  drawChart(){
     //implement drawing chart
  }
}

The problem is that inside a promise "this" in "this.drawChart()" no longer refers to the ChartsComponent class. How can I call a class method post promise?

Also, I cant put drawChart() inside the promise because it needs to use other class properties.

like image 309
Quinma Avatar asked Aug 03 '16 21:08

Quinma


2 Answers

When you use Arrow functions, the this is kept:

getData(){
  this.dataService.getData().then((data) => { // <-- changed here
    this.drawChart(data);
  });
}
like image 93
acdcjunior Avatar answered Oct 25 '22 03:10

acdcjunior


There are 2 solutions:

1) using "self":

     var self = this;
     ngOnInit() {
        self.getData();
     }

     getData(){
        self.dataService.getData().then(function (data) {
        self.drawChart(data);
     });

}

2) using "bind method" (or something like that):

.then(function (data) {
        this.drawChart(data);
     }).bind(this)

you can find so much information about this method, for example: Use of the JavaScript 'bind' method

I prefer first solution, because it helps make code more transparent.

like image 36
SirCapy Avatar answered Oct 25 '22 03:10

SirCapy