如何使用Spring Boot JSON接口数据在Angular项目中生成柱状图
Angular 渲染后端返回JSON为柱状图实现方案
1. 依赖安装
选用Angular生态适配性最好的ng2-charts(基于Chart.js封装)实现,首先安装对应依赖:
npm install ng2-charts chart.js
2. 模块配置
在项目根模块(通常为app.module.ts)中导入图表模块,同时确保已经导入HttpClientModule用于请求后端接口:
import { NgChartsModule } from 'ng2-charts'; import { HttpClientModule } from '@angular/common/http'; // 其他导入项... @NgModule({ imports: [ // 项目原有其他模块 HttpClientModule, NgChartsModule ], // 其他模块配置 }) export class AppModule { }
3. 组件逻辑编写
在对应组件中完成接口请求、数据格式转换、图表配置绑定:
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { ChartConfiguration, ChartType } from 'chart.js'; @Component({ selector: 'app-stat-bar-chart', templateUrl: './stat-bar-chart.component.html' }) export class StatBarChartComponent implements OnInit { // 柱状图类型声明 public barChartType: ChartType = 'bar'; // 图表数据配置 public barChartData: ChartConfiguration['data'] = { labels: [], // X轴维度对应值 datasets: [ { data: [], // Y轴数值对应值 label: '统计数值', backgroundColor: 'rgba(54, 162, 235, 0.6)' } ] }; // 图表样式配置 public barChartOptions: ChartConfiguration['options'] = { responsive: true, scales: { x: { title: { display: true, text: '分类' } }, y: { title: { display: true, text: '数值' }, min: 0 } } }; constructor(private http: HttpClient) {} ngOnInit(): void { // 替换为实际的Spring Boot接口地址 this.http.get<Record<string, number>>('http://你的后端接口地址').subscribe(res => { // 直接转换后端返回的对象为图表所需的数组格式 this.barChartData.labels = Object.keys(res); this.barChartData.datasets[0].data = Object.values(res); // *如果需要合并大小写不同的重复键(示例JSON中存在MANNOUBA/Mannouba、BENAROUS/Ben Arous这类疑似重复项),可以打开下方预处理逻辑: // const mergedData: Record<string, number> = {}; // Object.entries(res).forEach(([key, value]) => { // const formattedKey = key.toLowerCase(); // mergedData[formattedKey] = (mergedData[formattedKey] || 0) + value; // }); // this.barChartData.labels = Object.keys(mergedData); // this.barChartData.datasets[0].data = Object.values(mergedData); }) } }
4. 模板渲染
在组件对应的HTML文件中加入图表画布标签:
<div style="height: 600px; width: 100%;"> <canvas baseChart [data]="barChartData" [type]="barChartType" [options]="barChartOptions"> </canvas> </div>
内容的提问来源于stack exchange,提问作者Khalil Laouini
相关产品推荐
相关产品推荐

