I've encountered an issue with a function that generates an excel from an API request on my webpage. There's a download button that triggers the downloadCSV() function, which usually works fine except when I click it too quickly while navigating to the page.
Within the function, I subscribe to the data and populate an array used for generating the excel. Even if the array is empty, the excel still downloads immediately.
I'm considering two options:
1. Retrying the function if the excel turns out to be empty.
2. Waiting for the subscription to finish before executing.
downloadCSV (): void {
//list headers
const csvHeaders = [
'bunch of headers'
];
//initiate array
const data: any[] = [];
//fetch names for each customer
this.nameService.getNames().subscribe({
next: ({ names }) => {
//for each customer, fetch details
names.forEach(name => {
//get details
this.nameService.getPersonalData(name.firstName).pipe(
tap((data: Idata) => {
data.push({
'bunch of data points'
});
})
).subscribe(
{ error: (err) =>
{ console.error(err); } });
});
}
});
const filename = 'dataReport';
this.generateCSV(data, filename, reportHeaders);
}
generateCSV (data, filename, reportHeader): void {
new ngxCsv(data, filename, { headers: reportHeader, showTitle: true, title: this.customerDetails });
}
Essentially, the function involves fetching names, then using the first name to retrieve the desired data, and finally subscribing and generating an excel.
Currently, the excel instantly downloads without waiting for the data to be populated.