我是Angular2的新手,需要帮助。
我有一个JSON文件 - https://api.myjson.com/bins/ctyoh
{
"Semester": [
{
"queueName": "Science",
"totalCount": 300,
"unassignedCount": 10,
"subjectDetails": [
{
"subjectName": "Chemistry",
"sectionOne": 100,
"sectionTwo": 50,
"onTrackTradeCount": 150
},
{
"subjectName": "Biology",
"sectionOne": 100,
"sectionTwo": 50,
"sectionThree": 150
}
]
},
{
"queueName": "Arts",
"totalCount": 300,
"unassignedCount": 10,
"subjectDetails": [
{
"subjectName": "Indexing",
"sectionOne": 100,
"sectionTwo": 50,
"sectionThree": 150
}
]
},
{
"queueName": "Humanity",
"totalCount": 300,
"unassignedCount": 10,
"subjectDetails": [
{
"subjectName": "Indexing",
"sectionOne": 100,
"sectionTwo": 50,
"sectionThree": 150
}
]
}
]
}
如何访问totalCount
&
的Semester
来自变量的"subjectName": "Chemistry"
我的服务是这样的 -
private url = 'https://api.myjson.com/bins/ctyoh'
constructor(private http: Http) { }
getData(): Observable<any> {
return this.http.get(this.url)
.map((res: Response) => res.json(),
我订阅了我的Component的构造函数中的observable,如
constructor(private _chartData: ChartData) {}
ngOnInit() {
.subscribe(data => {
this.data = data;
console.log(data.Semester);
});
内部HTML我想像这样呈现值。
{{数据?.Semester.totalCount}}
我怎么能这样做?
提前致谢
答案 0 :(得分:2)
您需要ngFor
来展示totalCount
,并使用嵌套ngFor
来展示subjectName
:
在服务中,提取数组:
getData(): Observable<any> {
return this.http.get(this.url)
.map((res: Response) => res.json().Semester) // extract the array
}
在组件订阅中:
ngOnInit() {
this.myService.getData()
.subscribe(data => {
this.data = data;
})
}
然后你有ngFor
,它首先迭代数组中的所有对象,然后迭代每个对象中的子数组subjectDetails
。请注意下面的命名规则很差。改变它符合您的需求:
<div *ngFor="let x of data">
Total: {{x.totalCount}}
<div *ngFor="let y of x.subjectDetails">
Subject: {{y.subjectName}}
</div>
</div>
答案 1 :(得分:1)
您可以通过在其上运行循环并添加所有Semester
来获取totalCount
的总和,或者如果您的数组长度始终固定为3,您也可以在插值中添加它们。 / p>
循环方法:
for(let i=0; i< data.Semester.length; i++){
this.grandTotal += data.Semester[i].totalCount;
}
<p>Total: {{ grandTotal }}</p>
插补:
<p>Total: {{ data?.Semester[0]?.totalCount + data?.Semester[1]?.totalCount + data?.Semester[2]?.totalCount }}</p>
访问Chemistry
:
<p>{{ data?.Semester[0]?.subjectDetails[0]?.subjectName }}</p>