我怎样才能从这个json中获得信息来在angular 10中绘制它们呢?
{
"countries": [
{
"id": 1,
"name": "United States"
},
{
"id": 2,
"name": "India"
}
],
"states": [
{
"id": 1,
"countryId": 1,
"name": "Alabama"
},
{
"id": 2,
"countryId": 1,
"name": "Alaska"
}
]
}对于普通的json,我使用了这个,但是jeson有两个数组,它不允许我这样做
return this.http.get<Country[]>("./assets/data.json");尝试比较“Object Object”时出错。只允许数组和迭代器
<!-- html -->
<div *ngFor="let item of countri">
{{item.id}}
</div>模型
export interface Country {
id: number;
name: string;
}和我的订阅者
countri: Country[] = [];
this.countriesService.getCountries().subscribe(
countri => {
this.countri = countri;
console.log(countri);
},
err => console.log(err)
);发布于 2020-11-20 13:53:31
使用any。
第一种方法:
return this.http.get<any>("./assets/data.json");第二种方法是为你的数据定义一个合适的interface。
export interface IRequest {
countries: ICourtry[],
states: IState[]
}
export interface ICourtry{
id:number;
name: string;
}
export interface IState{
id:number;
name: string;
countryId: number;
}
return this.http.get<IRequest>("./assets/data.json");这里提到的错误(试图区分'object Object‘时出错)是因为你在模板中的某个地方使用了这个json,但它没有值。希望它将修复它或提供模板代码也。
发布于 2020-11-20 14:22:36
当您尝试使用对象而不是数组来循环访问ngFor时,通常会出现此错误。
如果您正在使用ngFor,
list.component.ts
data={
"countries": [
{
"id": 1,
"name": "United States"
},
{
"id": 2,
"name": "India"
}
],
"states": [
{
"id": 1,
"countryId": 1,
"name": "Alabama"
},
{
"id": 2,
"countryId": 1,
"name": "Alaska"
}
]
}list.component.html
<ul>
<li *ngFor="let item of data.countries">
{{item.name}}
</li>
</ul>或
<ul>
<li *ngFor="let item of data.states">
{{item.name}}
</li>发布于 2020-11-20 14:41:43
如错误所示,您最有可能尝试迭代对象而不是数组。此外,由于您获取的数据是异步的,因此您可以使用以下代码来避免任何错误。它使用异步管道和保险箱(?)操作符。
.ts
jsonData;
ngOnInit() {
this.jsonData = this.http.get('./assets/data.json');
}模板
<div *ngFor="let country of (jsonData | async)?.countries">
{{ country | json}}
</div>
<div *ngFor="let state of (jsonData | async)?.states">
{{ state | json}}
</div>https://stackoverflow.com/questions/64924402
复制相似问题