I am currently using Papa Parse with Angular 2 to load a csv list into a list and I want to be able to pass that list through to another component. I am able to read the csv data and print them with a console log but I am unable to address the results of the parsed data outside the 'complete' function. I know that this is because parsing a file is a asynchronous process and that I have to work with a callback function. I tried to fix this with a callback function but I am still not able to use the data outside the 'complete' function from Papa Parse itself.
This is an example of something I tried, but here the listOfLoads is undefined in the convertloads method, not in any other normal synchronous method.
export class AppComponent {
listOfLoads: Load[] = [];
constructor(){
}
importFile(fileInput: any, callBack) {
let listOfLoads: Load[] = [];
let file = fileInput.target.files[0];
let result = Papa.parse(fileInput.target.files[0], {
complete: function (results) {
callBack(results.data);
},
header: true,
delimiter: ";"
});
}
convertLoads(data) {
this.listOfLoads = deserialize<Load[]>(Load, data);
}
}
Is there a way to put the data in a list and use it in an other component? I've searched everywhere for a solution.
You can give your component function to Papaparse. Once Papaparse loads data it will trigger your function. Or you can create an observable and when data load completed you can do whatever want in subscribe block.
I created a working plunkr for you. You can look at this.