You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 11项目中如何将接口返回的数组数据导入Highcharts

Angular 11 + TypeScript 对接 Highcharts 实现测验数据可视化步骤

1. 安装依赖包

执行npm命令安装Highcharts相关依赖:
npm install highcharts highcharts-angular --save
安装完成后在对应功能模块(AppModule或业务子模块)中导入图表模块:

import { HighchartsChartModule } from 'highcharts-angular';

@NgModule({
  imports: [
    // 其他已有导入项
    HighchartsChartModule
  ]
})
export class AppModule { }

2. 定义TS类型适配接口返回结构

提前定义和接口返回匹配的类型,避免TypeScript类型报错:

// 单条测验记录类型
interface QuizRemark {
  Quiz_Title: string;
  Passed: string;
  Failed: string;
}
// 接口完整返回结构类型
interface QuizApiResponse {
  message: string;
  error: boolean;
  "error code": number;
  line: string;
  quizRemarks: QuizRemark[];
}

3. 组件中请求接口并转换为Highcharts适配格式

在业务组件中完成接口请求、数据转换、图表参数配置:

import { Component, OnInit } from '@angular/core';
import * as Highcharts from 'highcharts';
import { YourApiService } from './your-api.service'; // 替换为你自己的接口请求服务

@Component({
  selector: 'app-quiz-chart',
  templateUrl: './quiz-chart.component.html'
})
export class QuizChartComponent implements OnInit {
  Highcharts: typeof Highcharts = Highcharts;
  chartOptions: Highcharts.Options = {};

  constructor(private apiService: YourApiService) {}

  ngOnInit(): void {
    // 调用接口获取测验数据
    this.apiService.getQuizRemarks().subscribe((res: QuizApiResponse) => {
      const rawData = res.quizRemarks;
      // 转换为Highcharts需要的格式,注意把字符串类型的数值转为数字
      const xAxisCategories = rawData.map(item => item.Quiz_Title);
      const passedSeries = rawData.map(item => Number(item.Passed));
      const failedSeries = rawData.map(item => Number(item.Failed));

      // 这里以柱状图为例做配置,可按需切换其他图表类型
      this.chartOptions = {
        chart: {
          type: 'column'
        },
        title: {
          text: '测验通过/失败统计'
        },
        xAxis: {
          categories: xAxisCategories,
          crosshair: true
        },
        yAxis: {
          min: 0,
          title: {
            text: '人次'
          }
        },
        series: [
          {
            name: '通过',
            type: 'column',
            data: passedSeries
          },
          {
            name: '失败',
            type: 'column',
            data: failedSeries
          }
        ]
      };
    });
  }
}

4. 组件模板中渲染图表

在对应的html文件中加入highcharts渲染标签:

<highcharts-chart
  [Highcharts]="Highcharts"
  [options]="chartOptions"
  style="width: 100%; height: 500px; display: block;"
></highcharts-chart>
  • 后续用户完成新测验需要更新数据时,只需要重新请求接口、重赋值chartOptions的x轴分类和系列数据即可,Highcharts会自动触发重绘
  • 如需切换图表类型,仅修改chart.type参数即可,数据转换逻辑不需要调整

内容的提问来源于stack exchange,提问作者reginald bollosa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 17:39:01