typescript 防止将部分数组保存到本地存储中

pkmbmrz7  于 2023-01-21  发布在  TypeScript
关注(0)|答案(1)|浏览(133)

我试图阻止resultComment被保存到localStorage中,我该如何实现?目前,当我从浏览器中删除localStorage数据并计算结果时,结果会被推送到我的resultHistory数组中,只有结果和temperatureUnit会被保存到我想要的localStorage中,但在第二次计算中,resultComment也会被保存。我该如何防止这种情况,或者可以做些什么不同的事情?这里是StackBlitz:https://stackblitz.com/edit/angular-ivy-mdhnnt?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.module.ts,src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.css
重现问题的步骤:
1.清除本地存储数据并刷新页面,
1.在两个输入中键入数字并点击按钮-〉结果和单位被保存。
1.现在输入不同的数字,然后点击按钮-〉,现在resultComment也被保存了)。忽略奇怪的计算结果。它缺少的部分,我没有添加到StackBlitz。
组分ts

class HistoryResult {
  constructor(
    public result: number,
    public temperatureUnit: string,
    public resultComment?: string
  ) {}
}
  resultHistory: HistoryResult[] = []; 

//in ngOnInit iam initializing resultHistory so it stays on page when i refresh and adding comment to each result
ngOnInit() {
...
..code..
...
    this.resultHistory = JSON.parse(localStorage.getItem('result')) || [];
    this.resultHistory.map((item) => {
      item.resultComment = this.heatIndexService.determineComment(
        item.result,
        item.temperatureUnit
      );
    });
}
onCalculateButtonClick(): void {
    this.result = null;
    this.resultTemperatureUnit = this.temperatureUnit.value;
    if (this.heatIndexForm.invalid) {
      this.heatIndexForm.controls['temperature'].markAsDirty();
      this.heatIndexForm.controls['humidity'].markAsDirty();
      return;
    }
    this.result = this.heatIndexService.calculateHeatIndex(
      this.temperatureValue,
      this.humidityValue,
      this.resultTemperatureUnit.code
    );
    this.heatIndexService.saveResultInLocalStorage(
      this.result,
      this.temperatureUnit.value.code,
      this.resultHistory
    );
    this.resultHistory.map((item) => {
      item.resultComment = this.heatIndexService.determineComment(
        item.result,
        item.temperatureUnit
      );
    });
  }

服务功能

saveResultInLocalStorage(
    result: number,
    unit: string,
    historyResults: HistoryResult[]
  ): void {
    // Check if result is the same as last one
    if (
      historyResults.length === 0 ||
      historyResults.slice(-1)[0].result !== result
    ) {
      historyResults.push(new HistoryResult(result, unit));
      // Remove oldest result if more than 3 results
      if (historyResults.length > 3) {
        historyResults.shift();
      }
      localStorage.setItem('result', JSON.stringify(historyResults));
    }
  }

  determineComment(temperature: number, units: string): string {
    if (units === 'C') {
      temperature = (temperature * 9) / 5 + 32;
    }
    if (temperature >= 75 && temperature <= 90) {
      return 'Caution: fatigue is possible with prolonged exposure and activity. Continuing activity could result in heat cramps.';
    } else if (temperature > 90 && temperature <= 105) {
      return 'Extreme caution: heat cramps and heat exhaustion are possible. Continuing activity could result in heat stroke.';
    } else if (temperature > 105 && temperature <= 130) {
      return 'Danger: heat cramps and heat exhaustion are likely; heat stroke is probable with continued activity.';
    } else {
      return 'Extreme danger: heat stroke is imminent.';
    }
  }

以及显示以前计算结果的HTML

<p-table [value]="resultHistory" [tableStyle]="{'min-width': '50rem'}">
      <ng-template pTemplate="header">
          <tr>
              <th>Heat Index</th>
              <th class="heat-index-effect">Effect on the body</th>
          </tr>
      </ng-template>
      <ng-template pTemplate="body" let-history>
          <tr>
              <td>{{history.result | number : '1.2-2'}}&deg;{{history.temperatureUnit}}</td>
              <td>{{history.resultComment}}</td>
          </tr>
      </ng-template>
  </p-table>
0sgqnhkj

0sgqnhkj1#

开场白问题回答

您在调用this.historyResults.map(...)时改变数组,然后在调用localStorage.setItem(historyResults)时将该值保存在saveResultInLocalStorage中。
更改您的值,将其另存为一个新数组,其中只包含您想要的属性,然后调用localStorage.setItem(newValue)
要仅挑选所需的属性并保存它们,可以执行以下操作:

const resultsToSave: Pick<HistoryResult, 'result' | 'temperatureUnit'>[] = historyResults.map(h => ({ result: h.result, temperatureUnit: h.temperatureUnit }));
localStorage.setItem('result', JSON.stringify(resultsToSave));

除了使用上面的Pick来获取简化类型之外,还可以使用Omit,根据您指定的字段数量,Omit可能会更短,例如:

const resultsToSave: Omit<HistoryResult, 'resultComment'>[] = historyResults.map(h => ({ result: h.result, temperatureUnit: h.temperatureUnit }));

第一条评论回复

当你对历史结果执行.map()操作时,看起来你没有正确地重新分配值。尝试在迭代数组时返回一个新对象,并将其保存回自身。
从这里:

this.resultHistory.map((item) => {
  item.resultComment = this.determineComment(
    item.result,
    item.temperatureUnit
  );
});

对此:

this.resultHistory = this.resultHistory.map((item) => ({
  ...item,
  resultComment: this.determineComment(
    item.result,
    item.temperatureUnit
  ),
}));

相关问题