Функция обновления Chartjs работает неправильно - PullRequest
0 голосов
/ 23 января 2019

Я делаю Weatherapp j4f, но когда я пытаюсь визуализировать данные с помощью chartjs, функция обновления не работает должным образом.

Мне всегда нужно дважды нажать клавишу ввода, чтобы вызвать функцию onKeyPressed, где находится функция .update (), иначе график не будет обновлен.

/ 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, которая будет обновлять данные. Элемент ion с множеством P предназначен только для проверки, обновляются данные или нет. Когда я нажимаю клавишу ввода, данные в 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
  }
}

Я не хочу нажимать клавишу ввода дважды, пока данные на графике не будут обновлены

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...