我收到这个错误->类型"{}"不可分配给类型"NgIterable | null | undefined"。
我有一个名为collection的数组。最初设置为{},单击按钮后其值被初始化。
请参阅以下内容:-……….
list-resturant.component.html
<tr *ngFor="let item of collection">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.address}}</td>
<td>{{item.type}}</td>
</tr>
(列出resturant.component.ts(
export class ListResturantComponent implements OnInit {
constructor(private restobj:ResturantService) { }
collection={};
ngOnInit(): void {
this.restobj.getList().subscribe((result)=>{
console.warn(result);
this.collection=result; //here
});
}
请任何人帮助我。提前感谢
您需要将数组传递给*ngFor
,因此不必将collection
初始化为空对象{}
,只需将其初始化为空数组[]
:
collection = [];
然而,由于您是根据可观察结果设置集合的,因此您可以通过使用async
管道(而不是在控制器中订阅(直接在模板中使用可观察:
export class ListResturantComponent {
collection$ = this.restobj.getList();
constructor(private restobj:ResturantService) { }
}
<tr *ngFor="let item of collection$ | async">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.address}}</td>
<td>{{item.type}}</td>
</tr>