在打开控制台之前,Charts.js不会呈现图表

时间:2018-12-27 17:44:47

标签: angular chart.js

我有一个用Angular开发的Web应用程序,可以通过图表显示气象信息。

为此,我使用了Charts.js库,但是如果我转到页面,则画布是空的,就像这样:

empty canvas

但是,如果我打开控制台或使用CTRL +向下滚动鼠标,则会显示图表,如下所示:

chart over canvas

在这里您可以看到angular.ts:

import { Component, OnInit } from '@angular/core';
import {Router, ActivatedRoute,Params} from '@angular/router';
import {Chart} from 'chart.js'

import {WeatherService} from '../../services/weather.service';
import {Weather} from '../../models/weather';

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

export class ChartComponent implements OnInit {
  chart = [];

  public title: String;
  public weathers: Weather[];
  public weathersCity: Weather[];
  public identity;
  public token;
  public url: String;
  public page;
  public prev_page;
  public next_page;
  public cityPassed;
  public temperature=[];
  public dates=[];
  labels: any = [];
  data: any = [];

  constructor(    
    private _route:ActivatedRoute,
    private _router:Router,
    private _weatherService:WeatherService) { }

    ngOnInit() {
      this.showCityWeather();
      this.alertMessage();
    }

    alertMessage(){
      alert("By now the chart is not rendered until the console it´s open or you change the zoom(CTRL)+scroll down/up")
    }

    showCityWeather(){
      var localStorageRetrieve=localStorage.getItem("cityToView");

      var city=localStorageRetrieve;

      this._weatherService.showWheatherByCity(city).subscribe(
        response=>{if(!response){
          this._router.navigate(['/']);
        }else{
          this.weathersCity = response;
          console.log(this.weathersCity)
          //loop the object and add the data to the chart's array
          for(let i=0;i<this.weathersCity.length;i++){
            this.temperature.push(this.weathersCity[i].temperature)
            this.dates.push(this.weathersCity[i].date)          }
        }},
        error => {
          let errorMessage = <any>error;
          if (errorMessage !== null) {
            let body = JSON.parse(error._body); 
            console.log(body);
            }
          }
      )
    }

    ngAfterViewInit() {
      this.chart=new Chart('canvas',{
        type:'bar',
        data:{
          labels:this.dates,
          datasets:[{
            label: 'Temp. in Cº',
           data:this.temperature,
           backgroundColor: [


            ],
            borderColor: [


            ],
           borderWidth: 5
          }]
        },
        options: {
          scales: {
              yAxes: [{
                  ticks: {
                      beginAtZero:false
                  }
              }]
          }
      }
      })
      }
  }

这里是html:

<div class="chart" *ngIf="chart">
    <canvas #canvas id="canvas">{{ chart }}</canvas>
</div>

为什么会发生?

1 个答案:

答案 0 :(得分:0)

请尝试以下操作:

import { Component, OnInit } from '@angular/core';
import {Router, ActivatedRoute,Params} from '@angular/router';
import {Chart} from 'chart.js'

import {WeatherService} from '../../services/weather.service';
import {Weather} from '../../models/weather';

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

export class ChartComponent implements OnInit {
  chart = [];

  public title: String;
  public weathers: Weather[];
  public weathersCity: Weather[];
  public identity;
  public token;
  public url: String;
  public page;
  public prev_page;
  public next_page;
  public cityPassed;
  public temperature=[];
  public dates=[];
  labels: any = [];
  data: any = [];

  constructor(    
    private _route:ActivatedRoute,
    private _router:Router,
    private _weatherService:WeatherService) { }

    ngOnInit() {
      //this.showCityWeather();
      this.alertMessage();
    }

    alertMessage(){
      alert("By now the chart is not rendered until the console it´s open or you change the zoom(CTRL)+scroll down/up")
    }

    showCityWeather(){
      var localStorageRetrieve=localStorage.getItem("cityToView");

      var city=localStorageRetrieve;

      this._weatherService.showWheatherByCity(city).subscribe(
        response=>{if(!response){
          this._router.navigate(['/']);
        }else{
          this.weathersCity = response;
          console.log(this.weathersCity)
          //loop the object and add the data to the chart's array
          for(let i=0;i<this.weathersCity.length;i++){
            this.temperature.push(this.weathersCity[i].temperature)
            this.dates.push(this.weathersCity[i].date)          }
        }},
        error => {
          let errorMessage = <any>error;
          if (errorMessage !== null) {
            let body = JSON.parse(error._body); 
            console.log(body);
            }
          }
      )
    }
    showchart = false;
    ngAfterViewInit() {
      this.showCityWeather();
      this.chart=new Chart('canvas',{
        type:'bar',
        data:{
          labels:this.dates,
          datasets:[{
            label: 'Temp. in Cº',
           data:this.temperature,
           backgroundColor: [


            ],
            borderColor: [


            ],
           borderWidth: 5
          }]
        },
        options: {
          scales: {
              yAxes: [{
                  ticks: {
                      beginAtZero:false
                  }
              }]
          }
      }
      })
      setTimeout(() => {
      this.showchart = true;
      },100)
      }
  }
<div class="chart" *ngIf="showchart">
    <canvas #canvas id="canvas">{{ chart }}</canvas>
</div>