运行时出现Error trying to diff '[object Object]'错误,请求排查代码问题
Hey there, let's break down this error and get your table displaying API data correctly!
Why This Error Happens
The error ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed pops up because Angular's *ngFor directive can only loop through arrays or iterable objects. Right now, you're probably passing the entire API response object (a plain object with a data property) to *ngFor—and Angular can't iterate over that.
Let's Look at Your API Response
Your sample response has the actual data array nested inside the data key:
{"data":[{"action":"ok","btl_count":2,"created_user_nm":"jyjohn2","modified_dt":"Wed, 04 Apr 2018 14:32:10 GMT","order_sales_rep_cuid":"jyjohn2"...}]}
The array you need to render is response.data—not the full response object itself.
Step-by-Step Fix
1. Extract the Array in Your Component
When fetching data from the API, make sure you grab the nested data array instead of using the whole response:
// In your Angular component import { HttpClient } from '@angular/common/http'; export class YourTableComponent { tableData: any[] = []; // Initialize as empty array to avoid undefined issues constructor(private http: HttpClient) {} ngOnInit() { this.http.get('your-api-endpoint-url').subscribe((response: any) => { // Assign the nested data array to your component property this.tableData = response.data; }); } }
2. Update Your Template to Use the Array
Bind *ngFor to the tableData array in your HTML template:
<table> <thead> <tr> <th>Action</th> <th>BTL Count</th> <th>Created User</th> <!-- Add other headers as needed --> </tr> </thead> <tbody> <!-- Loop through the tableData array, not the full response --> <tr *ngFor="let item of tableData"> <td>{{ item.action }}</td> <td>{{ item.btl_count }}</td> <td>{{ item.created_user_nm }}</td> <!-- Render other fields here --> </tr> </tbody> </table>
3. Optional: Add Safety Checks
To handle cases where the API returns no data or a null data property, add a quick check in your template:
<tbody *ngIf="tableData && tableData.length"> <tr *ngFor="let item of tableData"> <!-- Your table cells --> </tr> </tbody> <tfoot *ngIf="!tableData || !tableData.length"> <tr> <td colspan="3">No data available</td> </tr> </tfoot>
That should fix the diff error and get your table showing the API data as expected!
内容的提问来源于stack exchange,提问作者Basha

