Как использовать сохраненные данные в Ionic / Angular? - PullRequest
0 голосов
/ 14 марта 2020

Я создаю приложение Ioni c, и у меня возникают проблемы с использованием данных, сохраненных с помощью this.storage.set. Когда я устанавливаю переменную на выход (var) и console.log в функции this.storage.get, я вижу, что она установлена ​​на значение моих сохраненных данных, но как только я пытаюсь использовать переменную в другом месте ( как на моем графике) ничего не появляется. При повторной попытке console.log это выглядит как неопределенное.

Кажется, я могу использовать только переменную внутри функции this.storage.get.

Как мне передать эти сохраненные данные в переменную?

tab2.page. html:

  <ion-toolbar>
    <ion-title>
      Stats
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>

<ion-card>
    <ion-card-header>
    Bar Chart
    </ion-card-header>
    <ion-card-content>
    <canvas #barCanvas></canvas>
    </ion-card-content>
</ion-card>

</ion-content>

tab2.page.ts:

import { Chart } from "chart.js";
import { Storage } from '@ionic/storage';

@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss']
})
export class Tab2Page implements OnInit {

  constructor(public storage:Storage) {}

  @ViewChild("barCanvas") barCanvas: ElementRef;

  h: any;
  a: any;
  s: any;
  e: any;
  w: any;

  ngOnInit() {

    this.storage.get('happiness').then( (val) => {
       this.h = val;
       console.log(this.h, val)
    })
    this.storage.get('anger').then( (val) => {
       this.a = val;
       console.log(this.a, val)
    })
    this.storage.get('stress').then( (val) => {
       this.s = val;
       console.log(this.s, val)
    })
    this.storage.get('energy').then( (val) => {
       this.e = val;
       console.log(this.e, val)
    })
    this.storage.get('worry').then( (val) => {
       this.w = val;
       console.log(this.w, val)
    })

    console.log(this.h, this.a, this.s, this.e, this.w)

    this.barChart = new Chart(this.barCanvas.nativeElement, {
      type: "bar",
      data: {
        labels: ["Happiness", "Anger", "Stress", "Energy", "Worry"],
        datasets: [
          {
            label: "% out of 100",
            data: [this.h, this.a, this.s, this.e, this.w],
            backgroundColor: [
              "rgba(255, 99, 132, 0.2)",
              "rgba(54, 162, 235, 0.2)",
              "rgba(255, 206, 86, 0.2)",
              "rgba(75, 192, 192, 0.2)",
              "rgba(153, 102, 255, 0.2)"
            ],
            borderColor: [
              "rgba(255,99,132,1)",
              "rgba(54, 162, 235, 1)",
              "rgba(255, 206, 86, 1)",
              "rgba(75, 192, 192, 1)",
              "rgba(153, 102, 255, 1)"
            ],
            borderWidth: 2
          }
        ]
      },
      options: {
        scales: {
          yAxes: [
            {
              ticks: {
                beginAtZero: true,
                stepSize: 20
              }
            }
          ]
        }
      }
    });
  }
}

Ответы [ 3 ]

0 голосов
/ 14 марта 2020

get() метод хранения Ioni c возвращает обещание. Так что вызов к нему асинхронный . И когда вы пытаетесь использовать переменные-члены (this.h и т. Д.) Для создания диаграммы, им еще не присвоены значения. В итоге вы используете undefined или предыдущие значения. Есть несколько способов решить эту проблему. Одним из быстрых способов было бы использовать forkJoin(). Попробуйте следующее

import {Observable} from 'rxjs/Observable';

ngOnInit() {
  Observable.forkJoin(
    {
      happiness: this.storage.get('happiness'),
      anger: this.storage.get('anger'),
      stress: this.storage.get('stress'),
      energy: this.storage.get('energy'),
      worry: this.storage.get('worry')
    }
  )
  .subscribe(result => {
    this.barChart = new Chart(this.barCanvas.nativeElement, {
      type: "bar",
      data: {
        labels: ["Happiness", "Anger", "Stress", "Energy", "Worry"],
        datasets: [
          {
            label: "% out of 100",
            data: [result.happiness, result.anger, result.stress, result.energy, result.worry],
            backgroundColor: [
              "rgba(255, 99, 132, 0.2)",
              "rgba(54, 162, 235, 0.2)",
              "rgba(255, 206, 86, 0.2)",
              "rgba(75, 192, 192, 0.2)",
              "rgba(153, 102, 255, 0.2)"
            ],
            borderColor: [
              "rgba(255,99,132,1)",
              "rgba(54, 162, 235, 1)",
              "rgba(255, 206, 86, 1)",
              "rgba(75, 192, 192, 1)",
              "rgba(153, 102, 255, 1)"
            ],
            borderWidth: 2
          }
        ]
      },
      options: {
        scales: {
          yAxes: [
            {
              ticks: {
                beginAtZero: true,
                stepSize: 20
              }
            }
          ]
        }
      }
    });
  });
}
0 голосов
/ 15 марта 2020

Попробуйте переписать ваши методы так, чтобы вы выполняли barChart только тогда, когда вы выполняли итерацию по всему хранилищу и все значения были получены.

Если я не ошибаюсь, вы можете использовать метод итератора forEach, который будет возвращать Promise после завершения всех итераций:

ngOnInit() {

    this.storage.forEach((value, key) => {

        switch(key) {
            case "happiness":
                this.h = value;
                break;
            case "anger":
                this.a = value;
                break;
            case "stress":
                this.s = value;
                break;
            default:
                console.log('no case matched')
                break;
        }

    }).then(() => {

        this.barChart = new Chart(this.barCanvas.nativeElement, {
            type: "bar",
            data: {
              labels: ["Happiness", "Anger", "Stress", "Energy", "Worry"],
              datasets: [
                {
                  label: "% out of 100",
                  data: [this.h, this.a, this.s, this.e, this.w],
                  backgroundColor: [
                    "rgba(255, 99, 132, 0.2)",
                    "rgba(54, 162, 235, 0.2)",
                    "rgba(255, 206, 86, 0.2)",
                    "rgba(75, 192, 192, 0.2)",
                    "rgba(153, 102, 255, 0.2)"
                  ],
                  borderColor: [
                    "rgba(255,99,132,1)",
                    "rgba(54, 162, 235, 1)",
                    "rgba(255, 206, 86, 1)",
                    "rgba(75, 192, 192, 1)",
                    "rgba(153, 102, 255, 1)"
                  ],
                  borderWidth: 2
                }
              ]
            },
            options: {
              scales: {
                yAxes: [
                  {
                    ticks: {
                      beginAtZero: true,
                      stepSize: 20
                    }
                  }
                ]
              }
            }
        });

    })
}
0 голосов
/ 14 марта 2020

используйте localStorage вместо Ionic Storage.

  • Установить данные localStorage.setItem('key', value)
  • Получить данные localStorage.getItem('key')
...