I’m trying to get data from external API. This is my Typescript function:
export class BarChartcomponent implements OnInit{
public chart: any;
data: any = [];
constructor(private service:PostService) { }
ngOnInit(): void {
this.service.getPosts().subscribe(response => {
this.data = response;
});
this.createChart();
};
}
I want to use "data" variable for further data manipulations, but when I try to use it outside the subscribe function it result "undefined". I know that is a scope error but I don’t know how to fix it.
2
Answers
you have 2 way
1: use promise and then to know when data recived
2: call your method in subscribe
If
this.data
becomes available only asynchronously, you can use a promise:Then, instead of using
this.data
directly in a synchronous function:you must
await
its value in an asynchronous function:Note that this make the
someFunction
also asynchronous, so that its return value (if it has any), must also beawait
ed. You can never get rid of asynchronousness once it is introduced.