Currently, I am working on a task that involves implementing two nested for loops in my code. The primary objective of the first loop is to make an API call, which is dependent on the IDs selected by the user. Unfortunately, the limitation of passing only one ID at a time to the API poses a challenge. The nested loop is responsible for processing the data returned by the API and storing it in an array. My ultimate goal is to consolidate all the data into a single array and transfer it to a child component using @Input(). Although I experimented with using a Promise to accomplish this task, there seems to be an issue that needs resolving. Specifically, I want the ngOnChanges() function in the child component to trigger only after the completion of both for loops' execution. Below is the code snippet that outlines my approach:
Parent Component:
getData() {
let temp: MyObjectType[] = [];
let allDataToSend: MyObjectType[] = [];
return new Promise<MyObjectType[]>((resolve, reject) => {
for (let i = 0; i < this.userIdSelections.length; i++) {
this.dataService.getData(this.userIdSelections[i])
.subscribe(results => temp = results,
error => {
this.getRequestResult = <any>error;
},
() => {
for (let j = 0; j < temp.length; j++) {
allDataToSend.push({
Property1: temp[j].Property1,
Property2: temp[j].Property2,
Property3: temp[j].Property3,
Property4: temp[j].Property4,
});
}
}
);
}
resolve(allDataToSend);
});
}
finalResults() {
this.getData().then(response => {
this.FinalObjectSendToChild = response;
})
}
Parent Template:
<button mat-flat-button color="primary" (click)="finalResults()">Search</button>
<app-child [finalData]="FinalObjectSendToChild"></app-child>
Child Component:
export class ChildComponent implements OnChanges {
@Input() finalData: MyObjectType[];
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
public tableColumns = ['Property1', 'Property2', 'Property3', 'Property4'];
public tableData: any
constructor() { }
ngOnChanges(changes: SimpleChanges) {
if (changes.finalData) this.createTable();
}
createTable() {
console.log(this.finalData); // displays expected data
console.log(this.finalData.length); // however, always returns 0
// the table created is blank...
this.tableData = new MatTableDataSource(this.finalData);
this.tableData.sort = this.sort;
this.tableData.paginator = this.paginator;
}