gpt4 book ai didi

javascript - JSON 响应在数组中,但仍然抛出错误 "NgFor only supports binding to Iterables such as Arrays"

转载 作者:搜寻专家 更新时间:2023-10-30 21:39:57 24 4
gpt4 key购买 nike

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.

Object is array

最佳答案

data : any; 说数据可以是任何东西,但是 *ngFor 只接受 Iterables。将其更改为 array因为您正在加载异步,所以当第一次呈现 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com