Angular2使用管道获取非常深层的嵌套json值! * ngFor [英] Angular2 Getting very deep nested json value using pipe! *ngFor
问题描述
我在获取json值时遇到了麻烦,该值实际上是使用管道深度嵌套的.
Hi I am having trouble getting json value which is really deeply nested using pipe.
我在做什么错了?
我正在使用的管道
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'keyValues'
})
export class KeysPipe implements PipeTransform {
transform(value, args: string[]): any {
let keys = [];
for (let key in value) {
keys.push({
key: key,
value: value[key]
});
}
return keys;
}
}
Json我正在从服务器获取.
Json I'm getting from server.
data:
0: {
Profile: { ...
}
BasicInfo: { ...
}
introduceInfo: {
curriculum: { ...
}
experience: {
0: {
category: "Mentor"
year: "2011"
duration: "24"
}
1: {
category: "Student"
year: "2011"
duration: "14"
}
}
}
}
它实际上是一个巨大的json对象,但我已简化为仅显示需要获取的内容.
It's actually a huge json object but I've simplified to only show what I need to get.
我想获取类别的值(即"Mentor"和"Student".
I want to get the value of category (which is "Mentor"and "Student".
要做到这一点,我已经尝试了我的html
And to do so, I've tried in my html
<div *ngFor="let detail of teaInfo | keyValues">
<div *ngFor="let experience of detail.value['introduceInfo'] | keyValues">
<div *ngFor="let exp of experience.value['experience'] | keyValues">
<p class="fontstyle2">{{exp.value['category']}} {{exp.value['year']}}년 | {{ex.value['duration']}}개월</p>
</div>
</div>
</div>
我在这样的组件中获取了json对象.
And I'm getting my json object in my component like this.
teaInfo: any[];
getTeacherDetail(): void {
let params = new URLSearchParams();
params.set('gradeType', `${this.getVal2()}`)
params.set('subjectType', `${this.getVal3()}`)
params.set('district', `${this.getVal1()}`)
this.teaDetail.getTeachersDetail(params)
.subscribe(
teaInfo => this.teaInfo = teaInfo,
error => this.errorMessage = error
)
}
结果是我什么也没得到
我在做什么错了?
推荐答案
尝试解释JSON的样子,如下所示:
Trying to interpret how your JSON looks like, something like this:
{
"data":{
"0": {
"Profile":{
"prof":"prof"
},
"BasicInfo":{
"basic":"basic"
},
"introduceInfo":{
"curriculum": {
"curr":"curr"
},
"experience":{
"0":{
"category":"Mentor",
"year":"2011",
"duration":"24"
},
"1":{
"category":"Student",
"year":"2011",
"duration":"14"
}
}
}
}
}
}
在下面的示例中,我从data
中提取了值,所以:
In below example, I have extracted the values from data
, so:
.map(res => res.json().data)
要达到值Mentor
和Student
,请首先将管道更改为:
To reach values Mentor
and Student
, first change your pipe to this:
export class KeysPipe implements PipeTransform {
transform(value: any, args: any[] = null): any {
return Object.keys(value).map(key => value[key]);
}
}
并将您的HTML更改为此:
and change your HTML to this:
<div *ngFor="let detail of teaInfo | keyValues">
<div *ngFor="let experience of detail['introduceInfo']['experience'] | keyValues">
{{experience.category}}
</div>
</div>
这应该很好地工作:
这篇关于Angular2使用管道获取非常深层的嵌套json值! * ngFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!