json - Angular 8 - 创建从 POST 请求返回的 JSON 键/值列表
问题描述
我要做的就是:
- 从我的 JSON 响应中获取“monthYear” -> 将它们设置为名为xValues的列表变量
- 从我的 JSON 响应中获取“numSessionIds” -> 将它们设置为名为yValues的列表变量
我的 JSON 响应:(我添加了一些新的行和空格,以便在这篇文章中更容易阅读):
[
{
"monthYear": "Jan 20",
"numSessionIds": 2,
"monthInDateFormat": 1577768400000
},
{
"monthYear": "Feb 20",
"numSessionIds": 5,
"monthInDateFormat": 1580446800000
},
{
"monthYear": "Mar 20",
"numSessionIds": 0,
"monthInDateFormat": 1582952400000
}
]
我通过在chart.service.ts中调用这个函数来获取这些数据:
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
credentials: 'same-origin',
}),
};
callNumberOfSessionsSP():any{
return this.http.post(`${this.BASE_URL}/RESTAPI/reports/callNumberOfSessionsSP?startDate=2020-01-01&endDate=2022-01-01&frequency=monthly`,
this.httpOptions,{responseType: 'json', observe: 'response'}).subscribe()
}
构造函数和初始变量名称(chart.component.ts):
chartData: any;
xValues: any;
yValues: any;
constructor(private chartService:ChartService) { }
我的 ngOnInit 方法(chart.component.ts):
ngOnInit() {
this.chartData = this.chartService.callNumberOfSessionsSP();
this.xValues = ??????
this.yValues = ??????
}
这 ??????是我不确定该放什么的地方。我已经尝试过类似的事情:
this.xValues=this.chartData.monthYear;
this.xValues=JSON.parse(Object.keys(this.chartData));
解决方案
以下是我从 JSON 响应创建 xValues 和 yValues 列表的方法:
chart.component.ts:
xValues: string[] = [];
yValues: number[] = [];
constructor(private chartService: ChartService) {
this.chartService.callNumberOfSessionsSP().subscribe((data: any) => {
//console.log(data[0].monthYear);
for (let i = 0; i < data.length; i++) {
console.log(data[i].monthYear);
this.xValues.push(data[i].monthYear);
this.yValues.push(data[i].numSessionIds);
}
console.log("printing this.xValues: ");
console.log(this.xValues);
console.log("printing this.yValues: ");
console.log(this.yValues);
}
图表服务.ts:
callNumberOfSessionsSP(): any {
return this.http.post(`${this.BASE_URL}/RESTAPI/reports/callNumberOfSessionsSP?startDate=2021-01-01&endDate=2021-05-01&frequency=monthly`,
this.httpOptions).pipe(
map((data: []) => {
return data;
}), catchError(error => {
console.log(error);
return throwError('Error occurred while calling api of name "callNumberOfSessionsSP"');
})
)
}
说明:
我基本上只需要下面的 for 循环来使用 [i] 索引遍历每个 JSON 集的 3 个值(monthYear、numSessionIds、monthInDateFormat)。这使我可以使用 .monthYear 和 .numSessionIds 来获取 json 响应中特定键的特定列/值。
在我尝试 data.monthYear 之前,我只需要执行 data[i].monthYear。
for (let i = 0; i < data.length; i++) {
console.log(data[i].monthYear);
this.xValues.push(data[i].monthYear);
this.yValues.push(data[i].numSessionIds);
}
推荐阅读
- angular - 如何在角度单元测试中模拟组件中的 store.pipe
- xml - 如何使用 XSLT 2.0 将 csv 文件转换为结构化 XML 文件?
- css - 如何在 Windows 上将 docker nginx 与 express 和 react 应用程序连接起来
- c# - 在 IDbCommandTreeInterceptor (EF 6.4) 中访问查询参数
- javascript - 使用 CSS 和 JS 过滤表
- angular - Quill.register 未被识别为函数
- mysql - MySql:如何在单个“\”反斜杠上拆分字符串
- css - 实现 Google 自定义搜索时覆盖 CSS 样式
- java - 如何使用 Dart 加密视频文件?
- c# - C# discord bot 在我的服务器中获取成员数