TypeScript 文件
export class CompanyComponent {
apiService : APIService;
data : any;
private companyUrl = 'http://localhost:4000/api/company/';
constructor(apiService : APIService) {
this.apiService = apiService;
this.getCompanies(this.companyUrl);
}
getCompanies(url: any){
this.data = this.apiService.GET(url).map((response :Response)=>
response.json()).subscribe((response)=>{
this.data = response;
console.log(this.data);
})
}
响应数组
[
{"_id":"58f61a132d44240d085ca2fa","comapny_name":"Burslem
Spice","__v":1,"categories":["58f643382d44240d085ca2fb"]},<br>
{"_id":"590487964a45c56c0fa2911a","comapny_name":"Tiger
Bite","categories":[]}
]
HTML 文件
<div class="media">
<div class="media-left" >
<li class="media" *ngFor = "let comp of data" >
<label>{{comp}}</label>
</li>
</div>
</div>
上面的响应仍在数组中,但我收到此错误:
ERROR caused by: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
最佳答案
data : any;
表示数据可以是任何内容,但 *ngFor 只接受 Iterables。
将其更改为数组
因为您正在加载异步,所以当第一次渲染 dom 时,data
将是未定义的,因此 Angular 会提示。
export class CompanyComponent {
apiService : APIService;
data : Array; // or array
private companyUrl = 'http://localhost:4000/api/company/';
constructor(apiService : APIService) {
this.apiService = apiService;
this.getCompanies(this.companyUrl);
this.data = []
}
getCompanies(url: any){
this.apiService.GET(url).map((response :Response)=>
response.json()).subscribe((response)=>{
this.data = response;
console.log(this.data);
})
}
HTML
<div class="media">
<div class="media-left" >
<li class="media" *ngFor = "let comp of data" >
<label> {{comp.company_name}}</label>
</li>
</div>
</div>
关于javascript - JSON 响应位于数组中,但仍引发错误 "NgFor only supports binding to Iterables such as Arrays",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43696767/