我的项目中有以下模型
动物
private name: string;
private age: string;
private zooLocation: Zoo[];
动物园
private zooname: string;
private zooaddress: address;
在项目中,data
返回Animal[]
。因此,数据包含动物对象列表。我想要的是console.log()
所有可用的动物园位置。因此Animal
对象中可能有大约10个对象,其中每个对象可能包含多个Zoo
位置。
我要做的就是打印属于Zoo
对象的所有Animal
位置。
到目前为止我尝试过的事情:
this.animalList = data;
this.allZooLocation = this.animalList.zooLocation;
this.animalList.zooLocation;
显示错误
类型“ Animal []”上不存在属性“ zooLocation”
答案 0 :(得分:2)
这是因为this.animalList
是一个数组,没有zooLocation
属性。
您可以循环animalList
并从Animal
类型的元素中获取数据。像这样:
for (let animal of this.animalList) {
console.log(animal.zooLocation);
}
此代码在控制台中打印出每种动物的zooLocation
。如果您想在该位置执行其他操作,则可以将代码替换为console.log
。
答案 1 :(得分:0)
animalList基本上是一个数组,而不是json。尽管此“点”表示法以JSON格式工作,但该数组仍需要指出一个位置。
例如,animalList [0]表示对象在列表的第一个位置,依此类推。因此,您要打印的是animalList [i] .zooLocation,其中我将从0变为(arrayLength-1)。
您可以为此使用常规的for循环。例如:
for(let i=0; i<animalList.length; i++){
console.log(animalList[i].zooLocation);}
或者,还有多种其他方式可以解析打字稿数组中的数据,例如每个循环或使用
for(let animal of animalList){
console.log(animal)
}
答案 2 :(得分:0)
这是我的答案,
public AnimalList : Animal[] = [
{
name : 'name1',
age : "20",
zooLocation : [
{ zooname : "zooname1",
zooaddress : "zooaddress1"
},
{ zooname : "zooname2",
zooaddress : "zooaddress2"
},
{ zooname : "zooname3",
zooaddress : "zooaddress3"
},
]
},
{
name : 'name2',
age : "21",
zooLocation : [
{ zooname : "zooname4",
zooaddress : "zooaddress4"
},
{ zooname : "zooname5",
zooaddress : "zooaddress5"
}
]
}
]
在模板中,
<div *ngFor="let list of AnimalList">
<div>{{list.name}}</div>
<div *ngFor="let item of list.zooLocation">
{{item.zooname}}
{{item.zooaddress}}
</div>
</div>
结果
name1
zooname1 zooaddress1
zooname2 zooaddress2
zooname3 zooaddress3
name2
zooname4 zooaddress4
zooname5 zooaddress5
或者您可以在.ts
中使用它for(let j=0; j<this.AnimalList.length; j++){
console.log(this.AnimalList[j].zooLocation);
}