简体   繁体   English

如何在 Ionic/Angular 中使用保存的数据?

[英]How to use saved data in Ionic/Angular?

I am building an Ionic application, and am having trouble using the data I have saved with this.storage.set .我正在构建一个 Ionic 应用程序,并且在使用我用this.storage.set保存的数据时遇到了问题。 When I set a variable to the output (var) and console.log it within the this.storage.get function, I can see that it is set to the value of my saved data, but as soon as I try to use the variable elsewhere (like in my graph) nothing appears.当我在this.storage.get函数中为输出 (var) 和console.log设置一个变量时,我可以看到它被设置为我保存的数据的值,但是一旦我尝试使用该变量其他地方(如我的图表中)什么也没有出现。 When trying console.log again it appears as undefined.再次尝试console.log时,它显示为未定义。

It seems I can only use the variable inside the this.storage.get function.看来我只能使用this.storage.get函数中的变量。

How do I get this saved data into a variable?如何将这些保存的数据放入变量中?

tab2.page.html: 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: 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
              }
            }
          ]
        }
      }
    });
  }
}

use localStorage instead of Ionic Storage .使用localStorage而不是Ionic Storage

  • Set Data localStorage.setItem('key', value)设置数据localStorage.setItem('key', value)
  • Get Data localStorage.getItem('key')获取数据localStorage.getItem('key')

get() method of Ionic storage returns a promise. Ionic 存储的get()方法返回一个 promise。 So the call to it is asynchronous .所以对它的调用是异步的 And when you try to use the member variables ( this.h and so on) for creating the chart, they haven't been assigned values yet.当您尝试使用成员变量( this.h等)来创建图表时,它们还没有被赋值。 So you end up using undefined or previous values.所以你最终会使用undefined或以前的值。 There are multiple ways to solve this issue.有多种方法可以解决这个问题。 One quick way would be to use forkJoin() .一种快速的方法是使用forkJoin() Try the following尝试以下

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
              }
            }
          ]
        }
      }
    });
  });
}

Try re-writing your methods such that you only do the barChart when you have iterated across your storage and all values were retrieved.尝试重新编写您的方法,以便您仅在遍历存储并检索所有值时才执行 barChart。

If I am not mistaked you can use forEach iterator method which will return Promise after all the iterations were completed:如果我没记错的话,您可以使用 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
                    }
                  }
                ]
              }
            }
        });

    })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM