the scenario is i am having the file uploader, which accept .json,.csv file after having file, If i clicked on upload button ,then homeComponent call the service dataparser , which is having two function readJson readCsv, and readcsv
function
returning the observable other one returns array ,this is simple i have to call the both function
on if else and handle the subscriber and array on HomeComponent
But wait i do not want to handle these complexities at component level so i want to return only array of data on the home component page so, I have handle these on service but observable creating problem in this
**dataparser.service.ts having threee 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");
}
readJson method is returning array of objects and m is not empty if type of file is json its returning m to 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));
}})
}
readCsv method is returning empty varaiable(res) due to subscribe method is there any workaround through which i could get valve of res from readCsv function and i do not want subscribe this method anywhere because i do not want handle these two result on homeComponent page, so then how can i get the value of this res varaible from readCsv
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;
}
}
Advertisement
Answer
You cannot await Observables directly, however, you can await
a Promise. You can simply use the .toPromise()
method on the observables subscription. Consider the following:
const date = await dateSubscription.toPromise();
private async readCsv() {
let res: any[];
res= await this.ngxCsvParser.
parse(this.file, { header: this.header, delimiter: ',' }).toPromise()
if(res)
{
console.log(" i got m");
return res;
}
}