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.
When you use Arrow functions, the this
is kept:
getData(){
this.dataService.getData().then((data) => { // <-- changed here
this.drawChart(data);
});
}
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.
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