Ag Grid中gridApi.forEachNode无输出问题排查咨询
Hey there! Let's break down exactly what's going on here, and why your arrow functions aren't the culprit.
The Root Cause: Timing of Async Data Loading
Here's the key issue:
- The
gridReadyevent fires as soon as the AgGrid DOM is initialized—this happens early in your component's lifecycle, right around whenngOnInitruns. - Your
fetchcall inngOnInitis asynchronous. WhengridReadytriggers, the API request hasn't finished yet, sorowDatais still empty. That's why callinggridApi.forEachNodedoesn't log anything—there are no rows to iterate over! - When you click your button later, the async request has already completed,
rowDatais populated with employee data, and AgGrid has rendered those rows. So the sameforEachNodelogic works perfectly.
Why Arrow Functions Aren't the Problem
Your arrow function in the fetch callback is actually working correctly! Arrow functions preserve the this context of the component, so this.rowData = out.data is properly updating your component's rowData property. No scope issues here.
Fixes to Make It Work
Here are two reliable ways to run your row iteration logic once the data is ready:
1. Iterate After Data Finishes Loading
Wait until your API response comes back, then trigger the iteration—just make sure the gridApi is already initialized first:
private gridApi: any; OnGridReady(params: any) { // Store the grid reference for later use this.gridApi = params.api; } ngOnInit() { fetch('http://dummy.restapiexample.com/api/v1/employees') .then(res => res.json()) .then((out) => { this.rowData = out.data; // Now that data is loaded, iterate if gridApi exists if (this.gridApi) { this.gridApi.forEachNode(node => { console.log('Row data:', node.data); }); } }) .catch(err => console.error(err)); }
2. Use AgGrid's rowDataChanged Event
AgGrid emits a rowDataChanged event whenever the rowData property is updated. You can hook into this to run your iteration logic automatically:
First, add the event to your template:
<ag-grid-angular #agGrid style="width: 100%; height: 100%; " class="ag-theme-alpine" [sideBar]="sidebar" [ngClass]="theme" [rowData]="rowData" [columnDefs]="columnDefs" [domLayout]="domLayout" rowSelection="multiple" [gridOptions]="gridOptions" (gridReady)="OnGridReady($event)" (rowDataChanged)="onRowDataChanged($event)" > </ag-grid-angular>
Then add the handler in your component:
private gridApi: any; OnGridReady(params: any) { this.gridApi = params.api; } onRowDataChanged(params: any) { this.gridApi.forEachNode(node => { console.log('Row data after update:', node.data); }); }
Either approach will ensure you're only trying to iterate over rows once the data is actually present in the grid.
内容的提问来源于stack exchange,提问作者Rishi JS




