Angular *ngFor循环报错:Type '{}'无法分配给NgIterable类型
解决Angular *ngFor类型不匹配错误
错误原因
你将collection初始化为空对象{},但*ngFor仅支持遍历可迭代类型(如数组、Set等),空对象不属于这类,因此TypeScript类型检查报错。后续赋值的result应为数组,但变量初始类型与目标类型不匹配。
具体解决方法
方法1:正确初始化并定义类型(推荐)
先明确数据类型,再将collection初始化为空数组:
- 在组件中定义数据接口(如果还没有):
interface Restaurant { id: number; name: string; address: string; type: string; }
- 修改
collection的声明与初始化:
export class ListResturantComponent implements OnInit { constructor(private restobj: ResturantService) { } // 定义为数组类型,初始值设为空数组 collection: Restaurant[] = []; ngOnInit(): void { this.restobj.getList().subscribe((result)=>{ console.warn(result); this.collection = result as Restaurant[]; }); } }
若暂时不确定result的具体类型,可先用any[]过渡:
collection: any[] = [];
方法2:用*ngIf确保可迭代后再渲染
如果不想修改变量初始化方式,可通过<ng-container>配合*ngIf判断collection是否为数组,避免渲染时的类型错误:
<ng-container *ngIf="collection && Array.isArray(collection)"> <tr *ngFor="let item of collection"> <td>{{item.id}}</td> <td>{{item.name}}</td> <td>{{item.address}}</td> <td>{{item.type}}</td> </tr> </ng-container>
注:Angular不允许在同一个元素上使用多个结构型指令(如*ngIf和*ngFor),因此需要用<ng-container>作为容器。
内容的提问来源于stack exchange,提问作者MANI_070
相关产品推荐
相关产品推荐

