Angular 2使用json中的对象数组获取对象

时间:2016-12-15 11:54:12

标签: json http angular getjson

我从json得到一个带有一个对象数组的对象,但是这个类没有填充,所以我得到一个ndefined错误就是get:

  getFeatures()  {
    return this.http.get('http://localhost:8080/features')
      .map((response: Response) => response.json())
      .map(({features,Feature}) => new Features(features,Feature));
  }

在这里,我尝试将课程从班级中删除

public getFeatures(){
    this.featureService.getFeatures().subscribe(res => {
    this.featureArray = res.getFeatureArray();
    console.log("Uitkomst: "+ res);
    console.log("Uitkomst array: "+ res.getFeature(0).getID());
    //this.tekst = this.featureArray[0].getID();
    });

}

这是features.ts:

import {Feature} from "./Feature";
export class Features {

  constructor(public featuress: string , public feature : Feature[]){}

  public getFeature(i : number): Feature{
    return this.feature[i];
  }
  public getFeatureArray(): Feature[]{
    return this.feature;
  }

这是feature.ts:

export class Feature{

  constructor(public id : string, public name : string, public desciption : string, public keyword : string, public failedTest : boolean){}

  public getID(){
    return this.id;
  }

}

我也尝试将get更改为:

  getFeatures()  {
    return this.http.get('http://localhost:8080/features')
      .map((response: Response) => response.json())
      .map(({features,Feature[]}) => new Features(features,Feature[]));
  }

但它说:

  

,预期

'http://localhost:8080/features'=的json输出 {"features":[{"id":"1","name":"feature1","description":"Dit is Feature 1","keyword":"Feature","failed":false},{"id":"2","name":"feature2","description":"Dit is Feature 2","keyword":"Feature","failed":false}]}

1 个答案:

答案 0 :(得分:0)

我的错在于我现在把关键功能作为一个真正的字符串:

getFeatures()  {
    return this.http.get('http://localhost:8080/features')
      .map((response: Response) => response.json())
      .map(({features = [Feature]}) => new Features(features));
  }

这很有效。