我正在尝试设置项目数组,并使用以下代码推送到localStorage:
public onSubmit(thumbnail, quantity, product_name, product_price){
const data = {
thumbnail,
quantity,
product_name,
product_price
};
localStorage.setItem(this.items, JSON.stringify(data));
this.items.push(JSON.parse(localStorage.getItem(data)));
}
我收到以下错误:
'any []'类型的参数不能分配给'string'类型的参数。
对于localStorage.setItem(this.items,JSON.stringify(data));
“ {”缩略图类型的参数:任意;数量:任意product_name:任意; product_price:任意; }”不能分配给“字符串”类型的参数。
对此this.items.push(JSON.parse(localStorage.getItem(data)));
在我的HTML中:
<tr *ngFor="let item of items;">
<td>
<td><img src="../assets/images/gallery/{{item.thumbnail}}" /></td>
<td>{{item.quantity}} </td>
<td>{{item.product_name }}</td>
<td>{{item.product_price}} </td>
<td>{{item.quantity * item.product_price }}</td>
</tr>
答案 0 :(得分:1)
当您检出setItem
中的definition时,会发现问题:
storage.setItem(keyName, keyValue);
Parameters
keyName
A DOMString containing the name of the key you want to create/update.
keyValue
A DOMString containing the value you want to give the key you are creating/updating.
keyName
应该是字符串。您使用this.items
作为参数,显然是一个数组。
相反,您可以尝试类似
localStorage.setItem('items', JSON.stringify(data));
this.items.push(JSON.parse(localStorage.getItem('items')));
更新:我不应该发布此信息,而不要说您可能不想直接在Angular组件中使用localStorage
。至少将其外包给服务。有关更多详细信息,请查看this question。
答案 1 :(得分:0)
问题在于将数据保存到本地存储时。 localstorage setItem方法需要两个参数,第一个是localstorage内部属性的名称,第二个是要保存的数据。
正确的方法是
localStorage.setItem('myCat', JSON.stringify(data));
更多示例可以在docs
中找到答案 2 :(得分:0)
您应该使用一些字符串键通过此键将某些内容存储在本地存储中。我相信您想将项目存储在本地存储中。看起来像这样:
storageKey = 'MyDataStorageKey';
public onSubmit(thumbnail, quantity, product_name, product_price){
const data = {
thumbnail,
quantity,
product_name,
product_price
};
this.items.push(data);
localStorage.setItem(this.storageKey, JSON.stringify(this.items));
}
ngOnInit() {
const itemsStr = localStorage.getItem(this.storageKey);
this.items = itemsStr ? JSON.parse(itemsStr) : [];
}
答案 3 :(得分:0)
这不起作用,因此它不是一个答案,但是包含代码,因此它可能不在评论中 现在产品已保存到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>