繁体   English   中英

防止部分数组保存到 angular 中的 localStorage

[英]prevent part of array saving to localStorage in angular

我试图阻止将 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. 清除localStorage数据并刷新页面,
  2. 在两个输入中键入数字并单击按钮 -> 结果和单位被保存。
  3. 现在在输入中键入不同的数字并单击按钮 -> 现在 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>

开题回应

您在调用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 ,它可能会更短,具体取决于您指定的字段数量,例如:

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

第一次评论回复

当您.map()遍历历史结果时,您似乎没有正确地重新分配值。 遍历数组并将其保存回自身时,尝试返回一个新的 object。

由此:

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

暂无
暂无

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

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