Reputation: 3
I am trying to save the value
of parse array
into global array
.
but global array
showing me undefined
dataUrl: string = "assets/data.csv";
private data:[];
dataInit(){
this.papa.parse(this.dataUrl, {
download: true,
complete: (result) => {
// result.data.push(this.data);
this.data = result.data
// console.log(result.data, "inside parser");
// console.log(this.data, "global array");
}
});
}
ngOnInit() {
this.dataInit();
console.log(this.data, "inside onInit");
}
Console
undefined "inside onInit"
Upvotes: 0
Views: 2414
Reputation: 82
Because this.papa.parse function is asynchronous, you can't get value of data variable right after calling dataInit... better to do inside complete callback
dataUrl: string = "assets/data.csv";
private data:[];
dataInit() {
this.papa.parse(this.dataUrl, {
download: true,
complete: (result) => {
this.data = result.data
this.toDo();
}
});
}
ngOnInit() {
this.dataInit();
}
toDo(){
console.log(this.data, "global array");
}
Upvotes: 0
Reputation: 7156
The data will be available inside complete callback
. So console.log(this.data)
over there.
Reason:
complete
is a callback method which works asynchronously.
dataUrl: string = "assets/data.csv";
data = [];
dataInit(){
this.papa.parse(this.dataUrl, {
download: true,
complete: (result) => {
// result.data.push(this.data);
this.data = result.data
console.log(this.data);
}
});
}
ngOnInit() {
this.dataInit();
}
Upvotes: 1
Reputation: 86760
There are two reasons for that -
private data: Array<any>= [];
Upvotes: 1
Reputation: 1465
Put the console log inside the complete function of the async code.
Because the papa.parse
download code is asynchronous, the console log will show the initial value of data
because the results are not ready yet.
Upvotes: 0
Reputation: 1465
Change the initialization of the data property to something like
private data = [];
Or
private data: Array<T> = []
Instead of T type your array accordingly
Upvotes: 0