如何使用接口获取的JSON数据



我正在尝试从JSON数据创建一个手风琴。

我正在从json-server调用GET请求,并且能够成功地调用API。

我无法访问变量tileDatachildren的属性,显示错误:

属性'children'不存在类型'Tile[]'.

我不知道我哪里错了。

tileData!: Tile[];
getTileData() {
this.tileService.showTile().subscribe((data: any) => {
this.tileData = data;
console.log('this.tileData.children.name :>> ', this.tileData.children.name ); //Shows error
});
}

服务文件中的函数为

showTile() {
return this.http.get<Tile[]>('http://localhost:3000/data');
}

我已经创建了一个接口来存储获得的JSON数据,如下所示:

export interface Tile {
name: string;
image: string;
children: { name: string; image: string; url: string };
}

我收到的JSON数据如下:

{
"data": [
{
"name": "First",
"image": "https://img.freepik.com/free-vector/football-2022-tournament-cup-background_206725-604.jpg?size=626&ext=jpg",
"children": [
{
"name": "Firstone",
"image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
"url": "http://www.google.com"
},
{
"name": "Firsttwo",
"image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
"url": "http://www.google.com"
},
{
"name": "Firstthree",
"image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
"url": "http://www.google.com"
}
]
},
{
"name": "Second",
"image": "https://img.freepik.com/free-vector/football-2022-tournament-cup-background_206725-604.jpg?size=626&ext=jpg",
"children": [
{
"name": "Secondone",
"image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
"url": "http://www.google.com"
},
{
"name": "Secondtwo",
"image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
"url": "http://www.google.com"
},
{
"name": "Secondthree",
"image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
"url": "http://www.google.com"
}
]
}
]
}

第一期

您的JSON响应是一个包含data属性和Tile[]的对象。

使用mapfrom rxjs返回Observable<Tile[]>

import { map } from 'rxjs';
showTile() : Observable<Tile[]> {
return this.http.get<any>('http://localhost:3000/data')
.pipe(map((response: any) => response.data));
}

问题2

children属性是一个数组而不是一个对象。

export interface Tile {
name: string;
image: string;
children: { name: string; image: string; url: string }[];
}

问题3

要打印出name,您需要从每个title对象迭代titleDatachildren数组。

getTileData() {
this.tileService.showTile().subscribe((data: any) => {
this.tileData = data;
for (let title of this.tileData) {
for (let child of title.children) {
console.log('title.children.name :>> ', child.name);
}
}
});
}

Demo @ StackBlitz

您没有提到错误,但是,接口定义应该使用与data中相同的确切名称。

export interface Tile {
name: string;
image: string;
children: { name: string; image: string; url: string };
}

最新更新