You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 6中Material Autocomplete报错:对象不可迭代问题

问题分析与解决方案

错误含义解释

你遇到的这个错误ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.意思很明确:Angular的*ngFor指令只能用来遍历可迭代对象(比如数组、Set这类),但你现在给它绑定的是一个Observable对象,而不是Observable内部发出的数组数据,所以Angular不知道怎么去遍历它。

具体解决步骤

1. 给Observable加上async管道

你的filterVendor是一个Observable<IVendor[]>,它本身不是数组,而是一个会发射数组的数据流。在模板里使用Observable时,必须通过async管道来自动订阅这个数据流,并取出里面的数组值。修改你的HTML代码里的*ngFor部分:

<mat-option *ngFor="let vendor of filterVendor | async" [value]="vendor.VendorId">
  <span>{{vendor.VendorName}}</span>
</mat-option>

2. 移除冲突的表单绑定

另外,你的input标签同时使用了[formControl]和formControlName,这两个属性不能同时存在(它们都是用来绑定表单控件的,会产生冲突)。如果你的组件是直接用VendorCtrl这个FormControl实例,就删掉formControlName="VendorId":

<input matInput placeholder="VendorName" [matAutocomplete]="auto" [formControl]="VendorCtrl" />

3. 验证过滤函数的正确性

确认你的_filterVendor函数返回的确实是数组:你的代码里是用this.vendors.filter(...),filter方法本身就返回数组,这部分是没问题的,所以只要前面两步改完,应该就能正常渲染选项了。

完整修改后的HTML示例

<mat-form-field>
  <input matInput placeholder="VendorName" [matAutocomplete]="auto" [formControl]="VendorCtrl" />
  <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
    <mat-option *ngFor="let vendor of filterVendor | async" [value]="vendor.VendorId">
      <span>{{vendor.VendorName}}</span>
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

这样修改后,Angular就能正确订阅Observable拿到数组,*ngFor也能正常遍历渲染下拉选项了,那个“对象不可迭代”的错误也就消失了。

内容的提问来源于stack exchange,提问作者Ian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:16:48