我怎样才能从这个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,但它没有值。希望它将修复它或提供模板代码也。
https://stackoverflow.com/questions/64924402
复制相似问题