Angular调用Spring Boot GET请求返回数据生成图表异常问题排查
问题原因
- HTTP请求属于异步操作,调用
getSimulation方法发送请求后,subscribe内的回调函数不会立刻执行,需要等后端返回响应后才会触发,完成currentSimulation的赋值。 - 遍历
currentSimulation.dailyStatsList的代码是在ngOnInit中同步执行的,执行这段代码时请求还未返回,currentSimulation处于未初始化状态,因此无法拿到数据。 - HTML可以正常展示数据是因为Angular自带变更检测机制,请求完成给
currentSimulation赋值后会触发页面重新渲染,所以能正常展示最新数据,但你的图表填充逻辑只在初始化时执行了一次,后续不会自动重新运行。
解决方法
将填充图表数据的逻辑移动到请求的成功回调函数中,确保拿到返回数据后再执行填充逻辑,修改后的代码示例如下:
ngOnInit(): void { const id = this.route.snapshot.params['id']; this.getSimulation(id); for (let i = 0; i < 5; i++) { this.chartData[1].data.push(i * 2); } } getSimulation(id: string): void { this.controllerService.get(id).subscribe( (data) => { this.currentSimulation = data; console.log(data); // 拿到接口返回数据后再填充图表 for (let dailyStats of this.currentSimulation.dailyStatsList) { this.chartData[2].data.push(dailyStats.pi); } // 若使用ng2-charts这类依赖变更检测的图表库,需手动触发数据更新检测 this.chartData = [...this.chartData]; }, (error) => { console.log(error); } ); }
补充说明
- 可以在使用
currentSimulation前先判断是否有值,避免请求失败时出现空指针报错。 - 如果需要动态匹配图表标签,也可以在回调中根据
dailyStatsList的day字段重新生成chartLabel数组。
内容的提问来源于stack exchange,提问作者94michalg
相关产品推荐
相关产品推荐

