Отображение диаграммы перед получением данных — ChartJS — обновление каждую секунду

#javascript #angular #typescript #csv #charts

#javascript #угловатый #машинописный текст #csv #Диаграммы

Вопрос:

Я попытался отобразить диаграмму пончика на своем веб-сайте с данными из CSV-файлов. Но проблема в том, что когда я перезагружаю страницу, там нет данных и нет пончика, но когда я перехожу на другую страницу (без того же пути) и возвращаюсь на нужную страницу, появляется пончик, но у меня ошибка: «ошибка конфигурации ng-диаграмм, данных или наборов данных поля обязательны для отображения диаграммы неопределенной».

Более того, поскольку данные меняются каждую секунду, как обновлять диаграмму каждый раз?

Большое спасибо, я перепробовал все, что нашел на 4 первых страницах Google, но ничего…

HTML-КОД :

 <div class="doubleTrp" *ngIf="_focusedData$ | async">
  <div class="trpChart">
    <canvas baseChart
            [chartType]="chartType"
            [datasets]="chartDatasets"
            [labels]="chartLabels"
            [colors]="chartColors"
            [options]="chartOptions"
            [legend]="true"
            (chartHover)="chartHovered($event)"
            (chartClick)="chartClicked($event)">
    </canvas>
  </div>
</div>
 

Мой TS-файл :

 import {Component, OnInit, OnDestroy} from '@angular/core';
import { ChartType } from 'chart.js';
import { MultiDataSet, Label} from 'ng2-charts';
import { LineService } from '../services/line.service';
import {ActivatedRoute} from '@angular/router';
import { SingleLineComponent } from '../single-line/single-line.component';
import {combineLatest, Subscription} from 'rxjs';
import {filter, map} from 'rxjs/operators';

@Component({
  selector: 'app-trp-graph',
  templateUrl: './trp-graph.component.html',
  styleUrls: ['./trp-graph.component.scss']
})
export class TrpGraphComponent implements OnInit, OnDestroy{

  lineSubscription: Subscription;
  trpHorraire: number;
  trpPoste: number;
  chartType: ChartType;
  chartDatasets: Array<any>
  chartLabels: Array<any>;
  chartColors: Array<any>;
  chartOptions: any;

  constructor(private lineService: LineService,
              private route: ActivatedRoute) {
  }

  ngOnInit(): void {
    this.chartIt();
  }

  _focusedData$ = combineLatest(
    this.lineService.lineSubject.pipe(filter(x => x.length > 0)),
    this.route.params.pipe(filter(x => !!x.id), map(x => x.id -1))
  ).pipe(
    map(([csvs, id]) => csvs[id])
  );

  gestionData(): void {
    this.lineSubscription = this._focusedData$.subscribe(x => this.trpHorraire = x.trpHeureReel);
    this.lineSubscription = this._focusedData$.subscribe(x => this.trpPoste = x.trpPosteReel);
  }

  async chartIt() {
    await this.gestionData();

    this.chartType = 'doughnut';
    this.chartDatasets = [
      {data: [this.trpHorraire, 100 - this.trpHorraire], label: 'TrpHorraire'}
    ];
    this.chartLabels = ['TRP HORRAIRE'];
    this.chartColors = [
      {
        backgroundColor: ['rgb(0, 133, 86)', 'rgb(78, 107, 124)'],
        hoverBackgroundColor: ['rgb(30, 163, 116)', 'rgb(108, 137, 144)'],
        borderWidth: 2,
      }
    ];
    this.chartOptions = {
      responsive: true
    };
  }

  chartClicked(e: any): void { }
  chartHovered(e: any): void { }

  ngOnDestroy(): void {
    this.lineSubscription.unsubscribe();
  }

}
 

Таким образом, при смене страницы данные отображаются, но не при первой загрузке на правильной странице.

Любая помощь будет полезна, большое спасибо.

Ответ №1:

Я решил свою проблему, просто написав переменную в html-коде, а не в ts. Я надеюсь, что это полезно.

Смотрите код :

   <ng-template class="trpChart" #vertH>
    <canvas baseChart
            [chartType]="chartType"
            [datasets]="[
              {
              data: [this.trpHoraire, 100 - this.trpHoraire], label: 'TrpHoraire'
              }
            ]"
            [colors]="[{
              backgroundColor: ['rgb(130, 230, 0)', 'rgb(255, 255, 255)'],
              hoverBackgroundColor: ['rgb(185, 30, 30)', 'rgb(225, 225, 255)'],
              borderWidth: 1
            }]"
            [options]="{
              responsive: true,
              cutoutPercentage: 80,
              title : {
                display: true,
                text: 'TRP HORAIRE',
                fontSize: 25
              }
            }"
            [legend]="true"
            (chartHover)="chartHovered($event)"
            (chartClick)="chartClicked($event)">
    </canvas>
  </ng-template>
 

Для TS это :

 import {Component, OnInit, OnDestroy} from '@angular/core';
import { ChartType } from 'chart.js';
import { MultiDataSet, Label} from 'ng2-charts';
import { LineService } from '../services/line.service';
import {ActivatedRoute} from '@angular/router';
import { SingleLineComponent } from '../single-line/single-line.component';
import {combineLatest, Subscription} from 'rxjs';
import {filter, map} from 'rxjs/operators';

@Component({
  selector: 'app-trp-graph',
  templateUrl: './trp-graph.component.html',
  styleUrls: ['./trp-graph.component.scss']
})
export class TrpGraphComponent implements OnDestroy{

  lineSubscription: Subscription;
  lineSubscription2: Subscription;
  trpHoraire: number;
  trpPoste: number;
  chartType: ChartType;
  chartDatasets: Array<any> = [];
  chartColors: Array<any>;
  chartOptions: any;

  constructor(private lineService: LineService,
              private route: ActivatedRoute) {
    this.chartIt();
  }



  _focusedData$ = combineLatest(
    this.lineService.lineSubject.pipe(filter(x => x.length > 0)),
    this.route.params.pipe(filter(x => !!x.id), map(x => x.id -1))
  ).pipe(
    map(([csvs, id]) => csvs[id])
  );

  gestionData(): void {
    this.lineSubscription = this._focusedData$.subscribe(x => this.trpHoraire = x.trpHeureReel);
    this.lineSubscription2 = this._focusedData$.subscribe(x => this.trpPoste = x.trpPosteReel);
  }

  gestionColor() {
    if(this.trpHoraire < 50) {
      return 'rgb(225, 37, 27)';
    }
    else if(this.trpHoraire >= 50 amp;amp; this.trpHoraire < 80) {
      return 'rgb(255, 182, 0)';
    }
    else {
      return 'rgb(130, 230, 0)';
    }
  }

  async chartIt() {
    await this.gestionData();
    await this.gestionColor();

    this.chartType = 'doughnut';
    /*this.chartDatasets = [
      {data: [this.trpHorraire, 100 - this.trpHorraire], label: 'TrpHorraire'}
    ];*/
    //this.chartLabels = ['TRP HORRAIRE'];
    this.chartColors = [
      {
        backgroundColor: ['rgb(130, 230, 0)', 'rgb(255, 255, 255)'],
        hoverBackgroundColor: ['rgb(30, 163, 116)', 'rgb(225, 225, 255)'],
        borderWidth: 1,
      }
    ];
    this.chartOptions = {
      responsive: true,
      cutoutPercentage: 80,
      title : {
        display: true,
        text: 'test'
      }
    };
  }

  chartClicked(e: any): void { }
  chartHovered(e: any): void { }

  ngOnDestroy(): void {
    this.lineSubscription.unsubscribe();
    this.lineSubscription2.unsubscribe();
  }

}