Angular2使用管道获得非常深的嵌套json值! * ngFor

时间:2017-04-13 04:48:19

标签: json angular ngfor

您好我无法获取使用管道进行深度嵌套的json值。

我做错了什么?

管道我正在使用

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我是从服务器上来的。

data:
  0: {
    Profile: { ...
    }
    BasicInfo: { ...
    }
    introduceInfo: {
      curriculum: { ...
      }
      experience: {
        0: {
          category: "Mentor"
          year: "2011"
          duration: "24"
        }
        1: {
          category: "Student"
          year: "2011"
          duration: "14"
        }
      }
    }
  }

它实际上是一个巨大的json对象,但我已经简化为只显示我需要得到的东西。

我想获得类别的价值(即“导师”和“学生”。

为此,我尝试了我的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对象。

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
    )
}

结果是我什么都没得到

我做错了什么?

1 个答案:

答案 0 :(得分:2)

尝试解释您的JSON的样子,如下所示:

{
  "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中提取了值,所以:

.map(res => res.json().data)

要获得值MentorStudent,请先将管道更改为:

export class KeysPipe implements PipeTransform {
  transform(value: any, args: any[] = null): any {
    return Object.keys(value).map(key => value[key]);
  }
}

并将您的HTML更改为:

<div *ngFor="let detail of teaInfo | keyValues">
 <div *ngFor="let experience of detail['introduceInfo']['experience'] | keyValues">
    {{experience.category}}
 </div>
</div>

这应该很好用:

Demo