Búsqueda de sitios web

typescript - Obteniendo "Error de Highcharts #17" al crear un histograma (usando Highcharts con Angular 6)


Estoy intentando crear un histograma simple con Highcharts en Angular y estoy recibiendo el siguiente error:

ERROR Error: Highcharts error #17: www.highcharts.com/errors/17
    at Object.a.error (highcharts.js:10)
    at a.Chart.initSeries (highcharts.js:245)
    at highcharts.js:270
    at Array.forEach (<anonymous>)
    at a.each (highcharts.js:28)
    at a.Chart.firstRender (highcharts.js:270)
    at a.Chart.<anonymous> (highcharts.js:245)
    at a.fireEvent (highcharts.js:31)
    at a.Chart.init (highcharts.js:244)
    at a.Chart.getArgs (highcharts.js:244)

Estoy siguiendo el siguiente tutorial proporcionado por Highcharts:

https://www.highcharts.com/docs/chart-and-series-types/histogram-series

Después de leer sobre el error "tipo no existe" (error #17 de Highcharts), parece que Highcharts piensa que me falta un archivo de extensión llamado "highcharts-more.js." He probado muchas implementaciones diferentes que incluyen el archivo "highcharts-more.js" en la solución, sin embargo, no he tenido suerte resolviendo el error.

Aquí está mi código:

app.component.html

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/histogram-bellcurve.js"></script>

<div [chart]="testHistogram"></div>

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Chart } from 'angular-highcharts';
import * as Highcharts from 'highcharts';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
    public testHistogram: Chart;

    ngOnInit() {
        this.createHistogram();
    }

    createHistogram(): void {
        var options = {
            title: {
                text: 'Test Histogram'
            },
            xAxis: [{
                title: {
                    text: 'time (ms)'
                }
            }],
            yAxis: [{
                title: {
                    text: '# of items'
                }
            }],
            series: [{
                name: 'Lag Histogram',
                type: 'histogram',
                xAxis: 1,
                yAxis: 1,
                baseSeries: 1
                }, {
                data: [3.5, 3, 3.2, 3.1, 3.6, 3.9, 3.4]
            }]
        }

        this.testHistogram = new Chart(<any> options);
    }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';  //for the dashboard view
import { ChartModule } from 'angular-highcharts';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
      BrowserModule,
      FormsModule,
      ChartModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Soy consciente de que se hizo una pregunta similar sobre cómo crear un histograma con Highcharts y Angular (error #17 de Highcharts al agregar series al gráfico usando Angular 4). Sin embargo, estoy utilizando un enfoque muy simple referenciado directamente desde el sitio de Highcharts, y faltaban algunos detalles en la pregunta anterior.

Estoy pensando que usar el tipo de serie histogram no debería requerir el archivo "highcharts-more.js" y ya debería estar disponible siempre que se incluya el módulo "modules/histogram-bellcurve.js" y el archivo "highcharts.js".

Además, en mi archivo .ts, parece que cuando el atributo data se incluye dentro de la opción series, se produce el error. Sin embargo, si elimino el atributo data (algo que es necesario para crear el histograma), y hago que la opción series ya no sea un arreglo con 2 elementos, no recibo el error. Pero, por supuesto, aún no tengo un histograma de datos para mostrar. Esto me hace preguntarme si Highchart primero verifica el tipo de histograma de la opción series y sus atributos correspondientes requeridos (asegurándose de que todos estén especificados y configurados para coincidir con un gráfico de histograma), antes de considerar que un gráfico es del tipo "histograma" o si eso se decide únicamente por el tipo especificado, sin tener en cuenta los atributos incluidos/especificados.

Si alguien allá afuera tiene una solución que funcione para crear y llenar un histograma Highchart exitosamente usando Angular, me encantaría saber cómo se haría esto.

Respuesta #1

Este error se lanza cuando estás tratando de crear un gráfico con series que no existen. Veo que no importaste correctamente el módulo de histograma. Deberías eliminar las etiquetas <script> de tu archivo app.component.html e importar los módulos dentro de app.module.ts.

Además, para que funcione, necesitas importar el módulo apropiado en el archivo mencionado, así:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';  //for the dashboard view
import { ChartModule, HIGHCHARTS_MODULES } from 'angular-highcharts';
import * as histogram from 'highcharts/modules/histogram-bellcurve';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
      BrowserModule,
      FormsModule,
      ChartModule
  ],
  providers: [
      { provide: HIGHCHARTS_MODULES, useFactory: () => [histogram] }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Además, te recomiendo usar el envoltorio oficial highcharts-angular, que está muy claramente documentado y no deberías tener ningún problema al crear tu propio gráfico. Además, está mejor soportado que los no oficiales. Aquí está el enlace al paquete npm: https://www.npmjs.com/package/highcharts-angular

Artículos relacionados