【问题标题】:Overwriting problem in localstorage angular本地存储角度中的覆盖问题
【发布时间】:2021-10-26 13:17:16
【问题描述】:

我的项目有问题,当我按下“添加到收藏夹”按钮时,我试图在 localStorage 中添加不同的食谱,但如果我单击 3 个不同的食谱,它们会覆盖在 localStorage 中,而不是添加其中的每一个。如果有人可以有一点时间,我想在这里得到一些帮助。非常感谢

recipe.ts。 - 我这里有我后端的食谱,我获取它们并尝试将它们添加到 localStorage

ngOnInit() {
    this.getDataFromApi();
  }

  getDataFromApi() {
    this.service.getData().subscribe(
      (response) => {
        console.log('Response from API is', response);
        this.data = response;
      },
      (error) => {
        console.log('Error is', error);
      }
    );
  }

add(i: any) {
    localStorage.setItem('Recipe', JSON.stringify(this.data[i]));
    console.log('Added in localstorage' + i);

    if (localStorage.getItem('Recipe') === null) {
      alert('TEST');
    }
  }

  remove() {
    localStorage.removeItem('Recipe');
    console.log('I deleted from localStorage');
  }

HTML

<div *ngFor="let recipe of data; let i = index">
      <p>
        {{ recipe.title }}
      </p>
      <img src="{{ recipe.image }}" alt="" />
      <p>{{ recipe.description }}</p>
      <p>{{ recipe.calories }}</p>
      <p>{{ recipe.cookingTime }}</p>
      <p>{{ recipe._id }}</p>
      <button (click)="add(i)">Add to favorite</button>
      <button (click)="remove()">Remove from favorite</button>
    </div>

现在,如果我按添加到收藏夹,我可以在 localStorage 中看到食谱,但如果我按另一个添加到收藏夹,则现有的食谱会被新的食谱覆盖。如何解决将它们全部放在 localStorage 中而不被覆盖的问题?非常感谢

【问题讨论】:

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


    【解决方案1】:

    localStorage 只是一个简单的键值存储,每次调用localStorage.setItem('Recipe', ...) 时都会为键“Recipe”分配一个新值,类似于变量赋值。 如果您想在 localStorage 中存储多个食谱,您可以将所有值存储为一个数组,每次添加新值时,您都会获取先前存储的值并将新食谱推送到该数组中。这是一个可能的解决方案

    const recipes = JSON.parse(localStorage.getItem("Recipes")) || [];
    recipes.push(this.data[i]);
    localStorage.setItem("Recipes", JSON.stringify(recipes));
    

    如果您想以更健壮的方式在本地存储一堆数据,我还可以推荐使用 IndexedDB:https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API 和/或处理本地存储数据的库,例如 https://github.com/pouchdb/pouchdb

    【讨论】:

    • 嗨@west efan,感谢您的时间,您的解决方案有效,非常感谢。现在我可以看到了。 localStorage 中有不同的食谱,但是您知道如何从 localStorage 中删除我想要的食谱吗?如果我使用 removeItem,我会一次性删除所有这些。如果您知道如何删除我想要的,我将不胜感激。再次感谢您的宝贵时间和帮助。
    • 一旦你有了数组,你就可以使用这个数组来处理你的数据,在这种情况下你正在寻找的是拼接功能:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    • 完美,非常感谢您抽出宝贵时间。
    【解决方案2】:

    根据当前的实现,它将始终用最新的值覆盖localStorage 值,通常localStorage 使用keyvalue 存储任何数据,在您尝试add to fav 时,您总是传递了一个key,这就是为什么它用最新的覆盖。

    我已经修改了你的代码,请看一下,希望对你有帮助

    添加方法

    add(i: any) {
      let recipes = JSON.parse(localStorage.getItem("Recipe")) || [];
      recipes.push(this.data[i]); 
      localStorage.setItem('Recipe', JSON.stringify(recipes));
      console.log('Added in localstorage' + i);
    
      if (localStorage.getItem('Recipe') === null) {
        alert('TEST');
      }
    }
    

    您可能会遇到remove item 的问题,请查看

    HTML 代码

    <div *ngFor="let recipe of data; let i = index">
      <p>
        {{ recipe.title }}
      </p>
      <img src="{{ recipe.image }}" alt="" />
      <p>{{ recipe.description }}</p>
      <p>{{ recipe.calories }}</p>
      <p>{{ recipe.cookingTime }}</p>
      <p>{{ recipe._id }}</p>
      <button (click)="add(i)">Add to favorite</button>
      <!-- pass this  recipe object with remove method -->
      <button (click)="remove(recipe)">Remove from favorite</button>
      
    </div>
    

    删除方法

    remove(recipe) {
      let recipes = JSON.parse(localStorage.getItem("Recipe")) || [];
      if(recipes.length){
        recipes = recipes.filter((x:any) => x._id !== recipe._id); // this will remove the item from list
        localStorage.setItem('Recipe', JSON.stringify(recipes));
        console.log('I deleted from localStorage');
      } 
    }
    

    【讨论】:

    • 嗨 Suneel Kumar,感谢您的回答,非常感谢您的宝贵时间。我面临一个关于 remove 方法的问题,它说:参数'x'隐含地具有'any'类型并且不能使应用程序再次运行。你有什么想法我该如何解决这个问题?非常感谢
    • 嗨@tirbushonn23,我再次更新了我的答案,请看一下,这只是一个小改动,只需将这个.filter(x =&gt; .....更改为.filter((x: any) =&gt; .....
    • 嗨 Suneel,它工作得很好。非常感谢你所做的一切。祝你有美好的一天。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 2017-12-20
    • 2018-08-18
    相关资源
    最近更新 更多