【问题标题】:How do you update a value in local Storage array Angular 7你如何更新本地存储数组Angular 7中的值
【发布时间】:2019-08-20 09:06:54
【问题描述】:

我想要做的是更新数组中的单个值这是我到目前为止的代码,但它似乎不能正常工作,想知道是否有人能帮助我解决这个问题.

所以,我认为它的工作原理是它从 ngFor 获取索引位置以及数组的自动递增 id,确保它具有匹配项并将新名称推送到数组。

但这似乎不起作用,它执行 toastr 说它已经更新但它还没有在本地存储中

     public updateNameLocalStorage(Name, id, i ): void {
          const currentArray = this.storage.get(this.STORAGE_KEY);
          console.log(currentArray);
          for (i = 0; i < currentArray.length; ++i) {
               if (currentArray[i].id === id) {
                    currentArray.push({
                         Name: Name
                     });
                     // insert updated array to local storage
                     this.storage.set(this.STORAGE_KEY, currentArray);
                     this.notifiy.showInfo('Name Updated'  , '');
                } else {
                    this.notifiy.showFailure('Error'  , '');

                }

          }

这是数据的结构

【问题讨论】:

  • 您在哪里确定该值未更新?
  • 好的,但是你在哪里确定值没有更新?我还是什么都没看到。您是否在设置值后将其记录在某个地方?
  • 对不起,我不明白,我想如果我使用 if 语句来检查 id 是否存在,它会更改名称,如果不存在,它会发送通知说错误
  • 对不起,我不太明白。您正在更新存储值,显示吐司,但是您什么也没做。那么怎么知道数据没有更新呢?另外,storage 是什么?好像不是localStorage

标签: javascript angular ecmascript-6 angular-local-storage


【解决方案1】:

您正在使用push,它将一个元素附加到数组的末尾。如果您想使用给定 ID 更新值,只需直接访问索引并覆盖该值。此外,如果您只是推送{Name: Name},则数组中的对象不再具有id 属性。

类似这样的:

const currentArray = this.storage.get(this.STORAGE_KEY);
const index = currentArray.findIndex(e => e.id === id);
if(index >= 0) {
  currentArray[index] = {...currentArray[index], ...{Name:Name}}; 
  this.storage.set(this.STORAGE_KEY, currentArray);
  this.notifiy.showInfo('Name Updated'  , '');
} else {
  this.notifiy.showFailure('Error'  , '');
}

【讨论】:

    猜你喜欢
    • 2020-10-27
    • 2019-09-06
    • 2018-02-18
    • 2014-03-22
    • 1970-01-01
    • 2020-07-07
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多