根据数组索引从json文件获取数据

时间:2018-07-26 14:22:03

标签: json angular-http

我有angular 5应用程序,并有具有对象数组的json文件(test.json)。 例如。

{"A": {
        "accountName": "Apple",
        "type": "fruit",
        "shortName": "App"
    },
    "B": {
        "accountName": "Ball",
        "type": "Game",
        "shortName": "Ba"
    }}

我也将模型DATAMODEL作为

export class DATAMODEL {
    constructor(
        public partnerId: string,
        public accountName: string,
        public type: string,
        public shortName:string    ) {}
}

我需要根据功能中请求的键来获取该对象

this.DATAMODEL= this.setData("A"); //where "A" is the dataKey

并被叫到

    public setData(dataKey:string):DATAMODEL {

       this.httpService.get('../../myassets/test.json').subscribe(
  data => {
    dm:DATAMODEL;
    this.arrBirds = data as string [];   // FILL THE ARRAY WITH DATA.
    this.dm=new DATAMODEL('','','');
    this.dm.partnerId=partnerId;
    this.dm.accountName=this.arrBirds[dataKey]['accountName'];
    this.dm.type=this.arrBirds[dataKey]['type'];
    this.dm.shortName=this.arrBirds[dataKey]['shortName'];


  },
  (err: HttpErrorResponse) => {
    console.log (err.message);
  return null;
  }
); 

return this.dm;


      }

但是在订阅之前调用了该问题。我很高兴为此找到更好的解决方案。

0 个答案:

没有答案