繁体   English   中英

Angular 2从JSON中获取带有对象数组的对象

[英]Angular 2 get object with an array of objects from json

我从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 '= {"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}]}

我的错在于,我现在将关键功能当作一个真正的字符串:

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

这可行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM