【发布时间】: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