Tekk_Know Tekk_Know - 4 months ago 13
AngularJS Question

Angular 2 - Component property undefined in method

I have a property that is a custom class array. The array is populated with a call to a service which calls a web service for data. I have subscribed to the observable and I'm using the complete event to fire off a method which loads a graph.

The data the graph uses should come from the array which is populated during the subscribe, but when I attempt to do so in the method I am getting an undefined error on my component property. Why is this the case, I though that the component property should be accessible to methods in the same class.

export class MetricsComponent implements OnInit{
errorMessage: string;
metric: MetricData[] = [];

//constructor is used for dependency injection
constructor(public _metricsService: MetricsService){}

ngOnInit(): void {
console.log('talking to service...');
this._metricsService.getData()
.subscribe(
data => this.metric = data,
error => this.errorMessage = <any>error,
this.LoadChart
);
}

LoadChart(): void {
console.log(this.metric); // <== this returns as undefined
}

Answer

Use arrow functions to retain the scope of this.

ngOnInit(): void {
    console.log('talking to service...');
    this._metricsService.getData()
        .subscribe(
            data => this.metric = data,
            error => this.errorMessage = <any>error,
            () => this.LoadChart()
        );  
}