After thorough research on similar issues, I couldn't find a solution to my problem. Hence, I am posting this question again to seek clarification on why this issue is occurring.
I have developed a web application where users can download data by clicking a button on one of the pages. Everything was running smoothly until I introduced a FOR loop to fetch additional data and append it to a new array. Below is the code snippet for better understanding:
employee-list.component.ts
import { Component, OnInit } from '@angular/core';
import { RestApiService } from "../shared/rest-api.service";
@Component({
selector: 'app-employees-list',
templateUrl: './employees-list.component.html',
styleUrls: ['./employees-list.component.css']
})
export class EmployeesListComponent implements OnInit {
// Code block omitted for brevity
}
In the download()
method of this code, I am creating an array called reportData
, which I later convert to CSV format for downloading purposes.
However, I noticed that this specific array reportData
appears empty once we exit the
this.restApi.getEmployeeAsset(emp.id).subscribe
call within the parent for loop. This inconsistency baffles me, and I'm struggling to pinpoint the cause of this behavior.
To detect this issue, I logged results at two different points within the for loop - one before the API call's subscribe method (
console.log("Report Data is available here"+JSON.stringify(this.reportData))
) shows the populated reportData
, while the other after the subscribe method (console.log("Report data is empty here"+JSON.stringify(this.reportData))
) displays an empty array.
I would greatly appreciate any insights into what mistake I might be making and why this unexpected outcome is happening.
I encountered no errors and successfully downloaded the required file. However, it only contained the header column with no data. :(
Current workaround:
To address this issue temporarily, I moved the For loop logic from download()
to loadEmployees()
, which is then invoked under ngOnInit()
. This ensures that necessary data is loaded when the component is initialized or executed (though I acknowledge this as not being the most efficient approach).
loadEmployees() {
// Code block omitted for brevity
}
While this solution works, it is not optimal since the reportData
array is generated regardless of whether the Download button is clicked. Struggling with handling Promises or asynchronous coding, I adopted this method as a temporary fix.