数据输出是一个数组但需要输入'Month'
,'data1%'
之类的字符串,
分别在此.monthdata,this.data1data的'data2'
'data3'
,0th position
等。
this.monthdata
的输出结果为
['Jan','feb']
['Month','Jan','feb'] where 'Month' should come from jsondata.json
我在代码中提到过。
[{
"Month": "Jan",
"data1%": "58.2",
"data2": "90.38",
"data3": "87.4",
"data4": "80.85"
},
{
"Month": "feb",
"data1%": "57.2",
"data2": "90.38",
"data3": "57.4",
"data4": "85.85"
}
]
gethpData(): Observable<any> {
return this.http.get('assets/json/hfollder/jsondata.json')
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
const body = res.json();
return body || [];
}
private handleError(error: any) {
const errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
// alert('Server Error!');
return Observable.throw(errMsg);
}
<button id='btn1' (click)='getdata('btn1')'>btn1</button>
<button id='btn2' (click)='getdata('btn2')'>btn2</button>
<button id='btn3' (click)='getdata('btn3')'>btn3</button>
<button id='btn4' (click)='getdata('btn4')'>btn4</button>
import { service } ....................// imported here
constructor(public jsonDataService: service){}
getdata = (id) => {
this.jsonDataService.gethpData().subscribe(res => this.getPartOfData(id, res));
}
getPartOfData(id, res) {
switch (id) {
case 'btn1':
//here getting data as ['','',''.......] where empty strings are data
//required data output as ['Month','','',''....]
this.monthdata = res.map(el => el.Month);
break;
case 'btn2':
//here getting data as ['','',''.......] where empty strings are data
//required data output as ['data1%','','',''....]
this.data1data = res.map(el => el['data1%']);
break;
case 'btn3':
//here getting data as ['','',''.......] where empty strings are data
//required data output as ['data2','','',''....]
this.data2data = res.map(el => data2: el.data2);
break;
}
}
答案 0 :(得分:0)
你可以这样做:
this.monthdata = ['Month' , ...res.map(el => el.Month) ];
使用ES6的数组解构。 对其他人也一样。