I'm fetching data from an API stored in df_array
. The function Initdf()
is called with a button.
This component works and df_array
contains the data because I get it displayed in a table on the page.
When I try to print df_array
in the console though, it is empty.
Why is that and how can I access df_array?
component.ts:
export class DataframeComponent implements OnInit {
df_array: DfInit[] = [];
constructor(private restService: RestServiceDfinit) {}
ngOnInit(): void { }
Initdf() {
this.restService.postTickerGetDf().subscribe((response) => (this.df_array = response));
console.log(this.df_array);
}
}
CodePudding user response:
You are trying to print this.df_array before assigning the new value.
Try this:
export class DataframeComponent implements OnInit {
public df_array: DfInit[] = [];
constructor(private restService: RestServiceDfinit) {}
ngOnInit(): void {}
Initdf() {
this.restService.postTickerGetDf().subscribe((response) => {
/**
* this is an asyncronous function, it will be executed after a while
*/
this.df_array = response;
console.log(this.df_array);
});
/**
* This is executed BEFORE the previous block when there is no value yet
*/
console.log(this.df_array);
}
}
CodePudding user response:
You are logging outside of the subscribe function, which means before the API call is finished and got a response.
The subscribe function should be seen as a "callback" after the API call. Your code describes a log of an empty array, a call to an API and populating this array with the response from the API.
If you put your log inside the subscribe function, you should see what you expect.
CodePudding user response:
I would say that it's because your console.log is called before your subscription (which is asynchronous) has ended. As far as it is asynchronous it doesn't block the execution of your code and goes to your console.log() which is of course empty. Then:
Initdf() {
this.restService.postTickerGetDf().subscribe((response) => (this.df_array = response));
console.log(this.df_array);
}
That triggers the log before the subscription has ended.
Try to put you console.log in your subsciption and log the response or your array.
Initdf() {
this.restService.postTickerGetDf().subscribe(
(response) => {
this.df_array = response
console.log(this.df_array);
};
);
}