Линейный график JS в Angular / Ioni c устанавливает новые значения в начале с временной осью - PullRequest
0 голосов
/ 17 марта 2020

У меня есть линейный график JS в приложении Ionic / Angular, и когда я отправляю в него новые значения, диаграмма помещает новые значения в начале, а затем начинает l oop в течение периода времени , Когда я получаю sh новые значения, я сохраняю список в localStorage (), а затем повторно анализирую сохраненные данные, затем обновляю список, связанный с фактическим графиком. Когда я перезагружаю страницу, предоставленную ioni c, в браузере, однако, значения находятся в нужном месте. Моя проблема проиллюстрирована на этом скриншоте: a graph doing bad stuff.

Все данные, на которые не было указано, были переданы перед перезагрузкой.

Вот мой home.page.ts:

import { Component, OnInit, ViewChild, ElementRef} from '@angular/core';
import { map } from 'rxjs/operators';
import { promise } from 'protractor';
import { from, defer } from 'rxjs';
import { AlertController} from '@ionic/angular';
import { Chart, TimeUnit } from 'chart.js';
import { formatDate } from '@angular/common';
import { Router } from '@angular/router';
@Component({
    selector: 'app-home',
    templateUrl: './home.page.html',
    styleUrls: ['./home.page.scss'],

})

export class HomePage implements OnInit {
    @ViewChild('lineCanvas') barChart;
    private lineChart: Chart;
    constructor(public alertController: AlertController, public router: Router) { }
    happy: number;
    angry: number;
    stressy: number;
    energy: number;
    worry: number;
    bars: any;
    public happiness = [];
    public anger = [];
    public stress = [];
    public energetic = [];
    public worrier = [];
    public dates = [];
    ngOnInit() {
        if (localStorage.getItem("loginState") == "0" || localStorage.getItem("loginState") == null) {
            this.router.navigate(['/signin']);
        }
        else {
        }
        this.unit = "day";
        this.happy = 50;
        this.angry = 50;
        this.stressy = 50;
        this.energy = 50;
        this.worry = 50;
    }
    ionViewDidEnter() {
        this.keyParse();
        this.createLineChart();
    }
    createLineChart() {

        this.bars = new Chart(this.barChart.nativeElement, {
            type: 'line',
            data: {
                datasets: [{
                    label: 'Happiness',
                    data: this.happinessKey(),
                    backgroundColor: 'rgba(0,0,0,0)',
                    borderColor: '#62ff29',
                    borderWidth: 1
                }, {
                        label: 'Anger',
                        data: this.angerKey(),
                    backgroundColor: 'rgba(0,0,0,0)',
                    borderColor: '#ff0000',
                    borderWidth: 1
                }, {
                        label: 'Stress',
                        data: this.stressKey(),
                    backgroundColor: 'rgba(0,0,0,0)',
                    borderColor: '#cc7722',
                    borderWidth: 1
                }, {
                        label: 'Energy',
                        data: this.energyKey(),
                    backgroundColor: 'rgba(0,0,0,0)',
                    borderColor: '#ffff00',
                    borderWidth: 1
                }, {
                        label: 'Worry',
                        data: this.worryKey(),
                    backgroundColor: 'rgba(0,0,0,0)',
                    borderColor: '#41009c',
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    xAxes: [{
                        type: 'time',
                        time: {
                            unit: this.unit
                        }
                    }],
                    yAxes: [{
                        ticks: {
                            beginAtZero: true,
                            suggestedMax: 100
                        }
                    }]

                }
            }
        });
    }
    happinessKey() {
        let list = [];
        for (var i = 0; i < this.happiness.length; i++) {
            console.log("pushing: " + { x: this.dates[i], y: this.happiness[i] });
            list.push({ x: this.dates[i], y: this.happiness[i] });
        }
        console.log("happyList: " + this.happiness);
        console.log("list: " + list);
        return list;
    }
    angerKey() {
        let list = [];
        for (var i = 0; i < this.anger.length; i++) {
            list.push({ x: this.dates[i], y: this.anger[i] });
        }
        return list;
    }
    stressKey() {
        let list = [];
        for (var i = 0; i < this.stress.length; i++) {
            list.push({ x: this.dates[i], y: this.stress[i] });
        }
        return list;
    }
    energyKey() {
        let list = [];
        for (var i = 0; i < this.energetic.length; i++) {
            list.push({ x: this.dates[i], y: this.energetic[i] });
        }
        return list;
    }
    worryKey() {
        let list = [];
        for (var i = 0; i < this.worrier.length; i++) {
            list.push({ x: this.dates[i], y: this.worrier[i] });
        }
        return list;
    }
    unit: TimeUnit;
    async presentAlertConfirm(header1, message) {
        const alert = await this.alertController.create({
            header: header1,
            message: message,
            buttons: [
                {
                    text: 'But I like this app!',
                    role: 'cancel',
                    cssClass: 'secondary',
                    handler: (blah) => {
                        console.log('Confirm Cancel: blah');
                    }
                }, {
                    text: 'EXTERMINATE!',
                    handler: () => {
                        this.presentAlert("No can do", "Apple doesn't like closing the app through code, so you're going to have to do it manually.");
                    }
                }
            ]
        });

        await alert.present();
    }
    async presentAlert(header1, message) {
        const alert = await this.alertController.create({
            header: header1,
            message: message,
            buttons: [
                {
                    text: 'Okay',
                    handler: () => {
                        console.log('Confirm Okay');
                    }
                }
            ]
        });

        await alert.present();
    }
    save() {
        try {
            var data2 = [this.happy, this.angry, this.stressy, this.energy, this.worry]
            console.log(data2);
            var local = JSON.parse(localStorage.getItem("data"));
            if (local.dates != null) {
                local.dates.push(Date.now());
                local.data.push(data2);
            } else {
                local.dates = [];
                local.data = [];
                local.dates.push(Date.now());
                local.data.push(data2);
            }
            localStorage.setItem("data", JSON.stringify(local));
            console.log("Save: " + localStorage.getItem("data"));

        }
        catch (error) {
            console.warn(error);
            localStorage.setItem("data", JSON.stringify({ "data": [], "dates": [] }));
            this.save();
            }

        this.keyParse();
        };
    keyParse() {
        this.happiness = [];
        this.anger = [];
        this.stress = [];
        this.energetic = [];
        this.worrier = [];
        try {
            var dates = JSON.parse(localStorage.getItem("data")).dates;
            console.log(dates);
            var data = JSON.parse(localStorage.getItem("data")).data;
            console.log(data);
            console.log();
            for (var i = 0; i < dates.length; i++) {
                if (this.checkSubstrings(dates[i])) {
                    this.happiness.push(data[i][0]);
                    this.anger.push(data[i][1]);
                    this.stress.push(data[i][2]);
                    this.energetic.push(data[i][3]);
                    this.worrier.push(data[i][4]);
                    this.dates.push(dates[i]);
                }
            }
            this.createLineChart();
        }
        catch {}
    }
    checkSubstrings(val) {
        var now;
        now = new Date();
        var ago = new Date().setDate(now.getDate() - 7);
        console.log(formatDate(ago, "full", "en_GB"));
        console.log(val);
        if (val > ago) {
            console.log("yes");
                return true;
            }
        else {
            console.log("no");
                return false;
            }


    }

}

Вот верхний (важный) бит home.page.html:

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-menu-button></ion-menu-button>
    </ion-buttons>
    <ion-title>Home</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content><div id="content">
    <ion-card>
        <ion-card-content>
            <canvas #lineCanvas></canvas>
        </ion-card-content>
<!-- All the tags are properly closed and there are no errors in the html, just here for reference. -->

Я знаю, что мог бы использовать location.reload(), но не хочу, так как отсутствие текучести нежелательно.

...