首页 > 解决方案 > 如何避免 LocalStorage 覆盖 Angular 中的数据?

问题描述

我正在创建一个调度程序,我可以在其中添加我在一定时间内完成的任务。

每次我按下“停止”时,都会出现一个输入,我可以在其中编写我刚刚完成的任务,然后保存该时间跨度内经过的时间的开始、结束和长度。

我现在要修复的主要功能是“addTask()”,我正在尝试使用 LocalStorage 存储这些任务,但是每次我添加一些内容时,它都会被覆盖,而不是像列表一样被添加。

这是完整的代码:

HTML:

<div class="modalbox" [class.active]="modalboxActive">
  <div class="modal">
    <p>What did you do?</p>

    <input type="text" [(ngModel)]="activity.name" />
    <button (click)="addTask()" [disabled]="activity.name === ''">OK</button>
  </div>
</div>
<div class="boxSuper">
  <div class="boxLeft">
    <div class="containerUp">
      <button id="start" (click)="startTimer()">START</button>
      <button id="pause" (click)="pauseTimer()">PAUSE</button>
      <button id="stop" (click)="stopTimer()">STOP</button>
    </div>
    <div class="containerDown">
      <p>{{ display }}</p>
    </div>
  </div>
  <div class="boxRight">
    <div class="containerLeft">
      <ul class="listElementLeft" *ngFor="let item of tasks">
        <li>
          <span id="writings">Start:</span>
          <span>{{ item.start }}</span>
        </li>
        <li>
          <span id="writings">End:</span>
          <span>{{ item.end }}</span>
        </li>
        <li>
          <span id="writings">Length:</span>
          <span>{{ item.length }}</span>
        </li>
      </ul>
    </div>

    <div class="containerRight">
      <ul class="listElement" *ngFor="let item of tasks">
        <li>
          <span id="writings">Activity:</span>
          <span>{{ item.name }}</span>
        </li>
      </ul>
    </div>
  </div>
</div>

TS:

import { importExpr } from '@angular/compiler/src/output/output_ast';
import { Component, OnInit } from '@angular/core';
import { timer } from 'rxjs';
import { Activity } from '../activity';
import { Result } from '../result';

@Component({
  selector: 'app-timer',
  templateUrl: './timer.component.html',
  styleUrls: ['./timer.component.css'],
})
export class TimerComponent implements OnInit {
  ngOnInit() {}
  time: number = 0;
  display: string | undefined;
  interval: any;
  modalboxActive = false;
  startTime: string | undefined;
  endTime: string | undefined;

  activity: Activity = {
    name: '',
  };

  tasks: Result[] = [];

  startFunc() {
    this.startTime = new Date().toString().split(' ')[4];
  }

  endFunc() {
    this.endTime = new Date().toString().split(' ')[4];
  }

  addTask() {
    var el: Result = {
      name: this.activity.name,
      end: this.endTime,
      start: this.startTime,
      length: this.display,
    };
    localStorage.setItem('token', JSON.stringify(el));
    window.localStorage.getItem('token');
    this.tasks.push(el);
    this.activity.name = '';
    this.modalboxActive = false;
    this.resetTimer();
  }

  resetTimer() {
    console.log('reset');
    this.time = 0;
  }

  startTimer() {
    console.log('go');
    this.interval = setInterval(() => {
      if (this.time === 0) {
        this.time++;
      } else {
        this.time++;
      }
      this.display = this.transform(this.time);
    }, 1000);
    this.startFunc();
  }

  transform(value: number): string {
    var sec_num = value;
    var hours = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - hours * 3600) / 60);
    var seconds = sec_num - hours * 3600 - minutes * 60;
    return hours + ':' + minutes + ':' + seconds;
  }

  pauseTimer() {
    clearInterval(this.interval);
  }

  stopTimer() {
    console.log('show');
    this.modalboxActive = true;
    clearInterval(this.interval);
    this.endFunc();
  }
}

标签: angulartypescript

解决方案


localStorage 只是在单个位置写入单个对象并将其映射到键,在您的情况下为“令牌”。它总是会覆盖你所拥有的。

但是,也许您想做更多这样的事情:

var list = window.localStorage.getItem('token');
list.push(task)
localStorage.setItem('token', list);

推荐阅读