Angular项目中localStorage存储收藏菜谱发生覆盖问题如何解决
问题原因
你的代码使用固定key Recipe 每次仅写入单条菜谱数据到localStorage,新写入的内容会直接覆盖旧内容,因此无法存储多条收藏记录。
解决方案
将所有收藏菜谱存储为数组格式,新增收藏时先读取已有数组,追加新内容后再整体存回localStorage。
修改后的TypeScript代码
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) { // 1. 读取已有收藏列表,无数据则初始化为空数组 const savedRecipes = JSON.parse(localStorage.getItem('Recipe') || '[]'); const targetRecipe = this.data[i]; // 2. 校验避免重复收藏同一菜谱(可根据需求删除该逻辑) const isExist = savedRecipes.some(item => item._id === targetRecipe._id); if (isExist) { alert('该菜谱已在收藏列表中'); return; } // 3. 追加新菜谱后存回localStorage savedRecipes.push(targetRecipe); localStorage.setItem('Recipe', JSON.stringify(savedRecipes)); console.log('Added in localstorage,当前收藏总数:' + savedRecipes.length); } // 调整后的删除方法,支持删除单个指定收藏 remove(recipeId: string) { const savedRecipes = JSON.parse(localStorage.getItem('Recipe') || '[]'); // 过滤掉要删除的菜谱 const filteredRecipes = savedRecipes.filter(item => item._id !== recipeId); localStorage.setItem('Recipe', JSON.stringify(filteredRecipes)); console.log('已删除指定收藏,当前收藏总数:' + filteredRecipes.length); } // 可选:保留清空全部收藏的方法 clearAllFavorites() { localStorage.removeItem('Recipe'); console.log('I deleted all recipes from localStorage'); }
修改后的HTML模板代码
主要调整删除按钮的传参,将当前菜谱的唯一标识_id传入删除方法:
<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(recipe._id)">Remove from favorite</button> </div>
补充说明
- 所有收藏的菜谱都以数组格式存在localStorage中,可随时通过
JSON.parse(localStorage.getItem('Recipe') || '[]')读取使用 - 如果需要页面加载时就显示菜谱的收藏状态,可在
ngOnInit阶段读取收藏列表,给对应菜谱加状态标记即可
内容的提问来源于stack exchange,提问作者tirbushonn23
相关产品推荐
相关产品推荐

