刷新后本地存储被覆盖

时间:2019-04-06 17:10:29

标签: angular storage local ionic4

所以,我有一个json文件,Uid代表用户ID

    const ChartData = {
     dayId: this.dayId,
     calories: this.burned,
     date: this.jstoday
    };

    this.dataService.setData(this.Uid, ChartData);

我使用dataService将数据保存在localstorage上,在其中创建一个空数组(ChartTable),并使用userID键将该数组保存到localstorage中,每次用户将数据添加到存储中时,我都会将其数据推送到ChartData表。

import { Injectable } from "@angular/core";
import { Storage } from "@ionic/storage";

@Injectable({
  providedIn: "root"
})
export class DataService {

  private data = [];
  private ChartTable = [];

  constructor(private storage: Storage) { }

  setData(Uid, data) {

    this.data[Uid] = data;


    this.SaveData(Uid, this.data[Uid]);

  }

  getData(id) {
    return this.data[id];
  }

  SaveData(Uid, data) {
    //Pushing eachDay's data to table
    this.ChartTable.push(data);

    //Need to stringify to work
    this.storage.set(Uid, JSON.stringify(this.ChartTable));
    // Or to get a key/value pair
  }
 }

当我继续向数组中添加项目时,它们被推入ChartTable数组中并正常工作。然后我进入配置文件页面检查本地存储并向用户显示图表。

import { Component, OnInit, ViewChild } from '@angular/core';
import chartJs from 'chart.js';
import { Auth2Service } from 'src/app/services/auth2.service';
import { Storage } from '@ionic/storage';
import { Calendar } from '@ionic-native/calendar/ngx';
import { LocalNotifications } from '@ionic-native/local-notifications/ngx';
import { ActivatedRoute } from '@angular/router';
import { AngularFireAuth } from '@angular/fire/auth';


@Component({
  selector: 'app-profile',
  templateUrl: './profile.page.html',
  styleUrls: ['./profile.page.scss'],


})
export class ProfilePage implements OnInit {

  @ViewChild('barCanvas') barCanvas;

  ChartData = [];
  ChartDataLength: any;

  public val: any;
  private Uid: string;

  Calories = [];
  Dates = [];
  BackgroundColors = [];

  barChart: any;

  today = new Date();
  followingDay = new Date();

  jstoday = '';

  constructor(
    private afAuth: AngularFireAuth,
    public auth: Auth2Service,
    private localNotifications: LocalNotifications,
    private calendar: Calendar,
    private route: ActivatedRoute,
    private storage: Storage

  ) {

  }

  ngOnInit() {

    this.checkForUser();

    // Schedule a single notification
    this.localNotifications.schedule({
      text: 'Delayed ILocalNotification',
      trigger: { at: new Date(new Date().getTime() + 3600) },
      led: 'FF0000',
      sound: null
    });

    this.calendar.createCalendar('MyCalendar').then(
      (msg) => { console.log(msg); },
      (err) => { console.log(err); }
    );

  }

  getChart(context, chartType, data, options?) {
    return new chartJs(context, {
      data,
      options,
      type: chartType
    })
  }

  getBarChart(Calories, Dates, BackgroundColors) {

    const data = {
      labels: Dates,
      datasets: [{
        label: 'number of calories you burned',
        data: Calories,
        backgroundColor: BackgroundColors,
        borderWidth: 1
      }]
    };

    const options = {
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true
          }
        }],
        xAxes: [{
          ticks: {
            beginAtZero: true
          }
        }]
      }
    }

    return this.getChart(this.barCanvas.nativeElement, 'bar', data, options);

  }

  checkForUser() {

    this.afAuth.authState.subscribe(user => {

      if (user) {
        this.Uid = user.uid;

        this.val = this.storage.get(this.Uid).then((val) => {

          this.ChartData = JSON.parse(val);

          if (this.ChartData != null) {

            this.ChartData = Object.keys(this.ChartData).map(key => ({ type: key, value: this.ChartData[key] }));

            this.ChartDataLength = this.ChartData.length;

            for (let i = 0; i < this.ChartDataLength; i++) {
              this.Calories[i] = this.ChartData[i].value.calories;
              this.Dates[i] = this.ChartData[i].value.date;
              this.BackgroundColors[i] = 'rgb(0, 249, 186   )';
            }

            this.barChart = this.getBarChart(this.Calories, this.Dates, this.BackgroundColors);

          }

        });
      }
    });

  }

  logoutUser() {
    this.auth.logoutUser();
  }
}

问题在于,当我刷新页面并向ChartTable添加其他项目时,它会被覆盖,并且只有新数据显示在图表上。您知道如何解决此问题吗?

1 个答案:

答案 0 :(得分:0)

当您重新加载应用程序时,您的应用程序将重新初始化,并且所有现有数据将从内存中消失。因此,您需要将其重置回DataService的ChartTable。从本地存储取回后,您可以立即执行操作。

if (this.ChartData != null) {

            this.ChartData = Object.keys(this.ChartData).map(key => ({ type: key, value: this.ChartData[key] }));

            this.ChartDataLength = this.ChartData.length;
            this.dataService.ChartTable = this.ChartData;

          }

您需要将DataService注入到组件中,并且需要在ChartTable上编写getter和setter或将其公开。