来自Java后端的Angular 4中的空响应

时间:2018-09-01 09:54:53

标签: angular spring-boot httprequest httpresponse angular4-httpclient

我是Angular的新手,但遇到了问题。我想从Spring Boot后端获取数据到图形中。我从Angular应用程序发送了GET请求,尽管在控制台中看到它不是空的,但我还是收到了空的响应。你能帮我吗?

我的角度服务

getChartData(): Observable<Array<ChartDataParameters>> {
  return this.http.get<Array<ChartDataParameters>> ('http://127.0.0.1:8080/currency/chartData');
}

和使用此方法的组件

this.databaseService.getChartData().subscribe(d => {
  this.data_origin = d;
});

for (let i = 0; i < this.data_origin.length; i++) {
  this.data.push([this.data_origin[i].date, this.data_origin[i].prediction, this.data_origin[i].currency]);
}

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

您应该在Subscription中使用您的数据。另外,您实际上并不需要为要使用的数据创建太多变量。

this.databaseService.getChartData().subscribe(d => {
  this.data_origin = d;
});

for (let i = 0; i < this.data_origin.length; i++) {
  this.data.push([this.data_origin[i].date, this.data_origin[i].prediction, this.data_origin[i].currency]);
}

应该是

this.databaseService.getChartData().subscribe(d => {

  for (let i = 0; i < d.length; i++) {
    this.data.push([d[i].date, d[i].prediction, d[i].currency]);
  }

});

此外,我认为您在这里所做的事情有误。数据是否应该是一个对象数组,每个对象包含三个键datepredictioncurrency

如果是这样,我认为您可以将逻辑简化为:

this.databaseService.getChartData().subscribe(d => {

  this.data = d.map(datum => { date: datum.date, prediction: datum.prediction, currency: datum.currency })

});

答案 1 :(得分:0)

loop内移动subscribe

this.databaseService.getChartData().subscribe(d => {
  for (let i = 0; i < d.length; i++) {
    this.data.push([d[i].date, d[i].prediction, d[i].currency]);
  }
});