In this scenario, I have a file uploader that accepts .json and .csv files. When the upload button is clicked, the HomeComponent calls the service dataparser which has two functions: readJson and readCsv. One function returns an observable while the other returns an array. Instead of handling these complexities at the component level, I want to return only the array of data on the HomeComponent page. However, I am facing issues with observables in the service.
**dataparser.service.ts has three methods**
async uploadDocument() {
const type = this.checkType();
if(!type) return;
let m = type == "csv" ? await this.readCsv() : await this.readJson();
if(m){
console.log(m);
return m;
}
console.log(" m is empty");
}
The readJson method returns an array of objects and m is not empty if the file type is json. It returns m to the caller function on HomeComponent.
private readJson() {
return new Promise((resolve,reject) =>{
const fr: FileReader = new FileReader();
fr.readAsText(this.file);
fr.onerror = () =>{
fr.abort();
reject(new DOMException("Problem parsing input file."));
}
fr.onload = () =>{
resolve(JSON.parse(fr.result as string));
}})
}
The readCsv method returns an empty variable (res) due to the subscribe method. Is there any workaround to get the value of res from the readCsv function without subscribing? I do not want to handle these two results on the HomeComponent page.
private async readCsv() {
let res: any[];
this.ngxCsvParser.parse(this.file, { header: this.header, delimiter: ',' })
.pipe().subscribe((result: Array<any>) => {
// console.log('Result', result);
res = result;
}, (error: NgxCSVParserError) => {
console.log('Error', error);
});
if(res)
{
console.log(" i got m");
return res;
}
}