Chartjs更新功能无法正常工作

时间:2019-01-23 19:14:36

标签: ionic-framework

我正在制作Weatherapp j4f,但是当我尝试使用chartjs可视化数据时,更新功能无法正常工作。

我总是必须按两次Enter才能调用.update()函数所在的onKeyPressed函数,否则图表将不会更新。

/weather.page.html

<ion-header>
  <ion-toolbar>
    <ion-title center>
      Weather
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-searchbar [(ngModel)]="this.cityName" (keyup.enter)="onKeyPressed()"></ion-searchbar>
  <div *ngIf="weatherData">
    <ion-item>
      <ion-title>
        {{this.weatherData.name}}
      </ion-title>
    </ion-item>
    <ion-item>
      <p class="weather weather__currentTemperature">{{this.weatherData.main.temp}}°C</p>
      <p class="weather__maxTemperature">{{this.weatherData.main.temp_max}}°C</p>
      <p class="weather__minTemperature">{{this.weatherData.main.temp_min}}°C</p>
      <p>{{this.weatherData.main.humidity}}%</p>
      <p>{{this.weatherData.coord.lat}}</p>
      <p>{{this.weatherData.coord.lon}}</p>
    </ion-item>
  </div>
  <div *ngIf="forecastData.length != 0">
    <canvas id="lineCanvas"></canvas>
  </div>
</ion-content>

最重要的部分是最后一个带有画布和线图的div,而Serachbar带有onKeyPressed函数,该函数将更新数据。其中包含许多 P 的离子项目仅用于测试数据是否更新。当我按Enter键后, P 中的数据就会更新。

import { ChartsModule } from 'ng2-charts';
import { element } from 'protractor';
import { WeatherService } from './../service/weather.service';
import { Component, OnInit, ViewChild } from '@angular/core';

import { Chart } from "chart.js";
import { createText } from '@angular/core/src/view/text';

@Component({
  selector: 'app-weather',
  templateUrl: './weather.page.html',
  styleUrls: ['./weather.page.scss'],
})
export class WeatherPage implements OnInit {
  weatherData: any;
  cityName: string;
  forecastData = [];
  forecastLabel = [];
  lineChart;

  constructor(private weatherService: WeatherService) {
    this.getWeaterData();
    this.getForecastData();
  }

  /**
   * @description: is called when the weather tab gets selected
   * @function: retrieves the lineCanvas node and creates a chart with the current Forecast/Weather-Data
   */
  ionViewWillEnter(){
    var lineCanvas = document.getElementById("lineCanvas");
    this.lineChart = new Chart(lineCanvas, {
      type: 'line',
      data: {
        labels: this.forecastLabel,
        datasets: [{
          data: this.forecastData
        }]
      }
    });
  }

  ngOnInit() {}

  /**
  * @description: fetches the current weather-data
  * @function: hands over the data to the variable weatherData
  */
  getWeaterData() {
    this.weatherService.getCurrentWeather().subscribe((data) => {
      this.weatherData = data;
      // console.log(data);
    });
  }

  /**
   * @description: is called when the data from the searchbar gets submited
   * @function: updates the Forecast/Weather-Data
   */
  async onKeyPressed() {
    this.cityName = this.sanitize(this.cityName);
    this.weatherService.currentCity = "" + this.cityName;
    await this.getWeaterData();
    await this.getForecastData();
  }
  /**
   * @description: fetches the forecast (five days) and updates the linechart
   * @function: calls the getFiveDayForecast funtion from the WeatherService and 
   *            updates the data and the chart(s)
   */
  getForecastData() {
    this.weatherService.getFiveDayForecast().subscribe((data) => {
      let forecastList = data["list"];
      this.forecastData = [];
      this.forecastLabel = [];

      for (let i = 0; i < data["cnt"]; i++) {
        var avg = (forecastList[i].main.temp_max + forecastList[i].main.temp_min) / 2;
        var fullDate = forecastList[i].dt_txt;
        this.forecastData.push(avg);
        this.forecastLabel.push(fullDate);
      }
    });

    if(this.lineChart){
      this.lineChart.data.labels = this.forecastLabel;
      this.lineChart.data.datasets[0].data = this.forecastData;
      this.lineChart.update();
    }
  }

  /**
   * @description: sanitizes the input string from the searchbar
   * @function: filters out < > / \ & from the string and replaces it with unicode which will not be rendered
   * @param unsafeString: the string which will be sanitized from evil input
   */
  sanitize(unsafeString) {
    return unsafeString
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/\"/g, '&quot;')
      .replace(/\'/g, '&#39;'); // '&apos;' is not valid HTML 4
  }
}

我不想按两次Enter键,直到图表中的数据得到更新

0 个答案:

没有答案