Angular使用*ngFor遍历数据报错:仅支持数组等可迭代对象
That error happens because Angular's *ngFor can only loop through iterable values like arrays, but right now your environments variable is an object instead of an array. Let's walk through how to fix this:
1. Verify you're calling the correct service method
Looking at your code: your service has a getEnvironments() method that fetches data from the /environments endpoint, but your component is calling getContainers(). If you meant to load environment data, swap to using the correct service method:
this.docker.getEnvironments().subscribe(environments => { this.environments = environments; console.log(environments); // Check what this outputs in your browser console! });
2. Inspect the structure of your API response
Even if the API returns an array, it might be wrapped inside an object (like { "results": [...] }). Check the console.log output from your component:
- If it’s a direct array (e.g.,
[{...}, {...}]), assigningthis.environments = environmentswill work fine. - If it’s an object with the array nested in a property (like
response.dataorresponse.environments), extract that array explicitly:this.docker.getEnvironments().subscribe(response => { this.environments = response.environments; // Adjust the property name to match your actual API response });
3. Initialize your variable as an empty array
To avoid loading-time errors before the API call finishes, initialize your environments variable in the component as an empty array:
environments: any[] = [];
Once you ensure environments is an actual array, your *ngFor loop will render the table rows correctly.
内容的提问来源于stack exchange,提问作者user9793665

