Reputation: 23
I want to build chart using highchart module on Angular. The Object is provided from an API. This is the object I should have obtained.
{
"success": true,
"activity": [
{
"username": "aja_ditag_yo",
"activity": 0
}
]
}
So I build my service.ts to get those object and call it on my component.ts. This is my component.ts
import { Component, OnInit } from '@angular/core';
import * as Highcharts from 'highcharts';
import { AdminService } from 'src/app/services/admin.service';
@Component({
selector: 'app-linebarchart',
templateUrl: './linebarchart.component.html',
styleUrls: ['./linebarchart.component.scss']
})
export class LinebarchartComponent implements OnInit{
chartOptions:{} = {};
Highcharts = Highcharts;
dataRegister:any = {}
constructor(
public adminService: AdminService
) {
}
ngOnInit (): void {
this.adminService.getActivity().subscribe(data => {
this.dataRegister = data
this.chartOptions = {
// some highcarts config, and dataRegister is called
....
series: this.dataRegister.activity
}
})
}
}
Since the chartOptions
is inside subscribe
. chartOptions
returns undefined. So I moved the chartOptions
outside subscribe
and the highcharts appear on the page. But, the dataRegister.activity returns undefined. What should i do?
Upvotes: 0
Views: 525
Reputation: 68737
The function in subscribe
is called asynchronously after the data comes back. Which means your console.log
is called first. Use
this.adminService.getActivity().subscribe(data => {
this.dataRegister = data;
console.log(this.dataRegister.activity);
});
Upvotes: 2