Angular 使用Splice从本地存储中删除项

Angular 使用Splice从本地存储中删除项,angular,Angular,我正在将产品保存到localStorage,需要从localStorage中删除该项目。我正在使用 deleteItem(i){ localStorage.removeItem(i); localStorage.setItem(i, JSON.stringify(this.items)); this.items.splice(i,1); } 我从中得到函数的参数 <tr *ngFor="let item of items; let i = index"> <

我正在将产品保存到localStorage,需要从localStorage中删除该项目。我正在使用

deleteItem(i){
localStorage.removeItem(i);
localStorage.setItem(i, JSON.stringify(this.items));
this.items.splice(i,1);
}
我从中得到函数的参数

<tr *ngFor="let item of items; let i = index">
<td>
<button type="button" (click)="deleteItem(i)">X</button></td>
</tr>

X

这不管用。执行上述代码后,产品仍在localStorage中。

更改后必须将项目设置为localStorage

deleteItem(i){
const newItems=this.items.splice(i,1);
localStorage.setItem('items', JSON.stringify(newItems));
}

首先-
localStorage.setItem(i,JSON.stringify(this.items))
您正在使用
localStorage
键的项索引。它可能把事情搞砸了

处理
localStorage
(或任何第三方数据源)的最佳方法是创建getter和setter函数

getStorageItems(): any[] {
    try {
        return JSON.parse(localStorage.getItem('items'));
    } catch(err) {
        console.warn(err);
        return [];
    }
}

setStorageItems(items: any[]) {
    localStorage.setItem('items', JSON.stringify(items));
}
this.items
指的是组件的作用域,您应该在组件初始化中初始化它并从中派生视图

ngOnInit() {
    this.items = this.getStorageItems();
}


谢谢,Milad Ahmadi,但在执行代码后,该项仍在本地存储中。谢谢,fingeron。这似乎会从localStorage中删除该项目,但在完成将其部署到Web之前,我无法确定。我可以使用“ng serve”编译应用程序,没有错误,但当我使用“ng deploy”部署应用程序时,该应用程序就无法工作。没有错误消息,所以我不知道如何修复。没有错误通常意味着代码正常。我不知道您的部署过程中发生了什么,但在正确构建的应用程序中,
ng serve
ng build
<tr *ngFor="let item of items; let i = index">
    <td><button type="button" (click)="deleteItem(i)">X</button></td>
</tr>
deleteItem(i) {
    this.items.splice(i, 1);
    this.setStorageItems(this.items);
}