在开发模式下,items是一个数组,但是在部署应用程序后,它变成了一个对象,并且在控制台中出现以下错误: 找不到类型为“对象”的其他支持对象“ [对象对象]”。 NgFor仅支持绑定到Iterables,例如数组。
在组件中:
items = [];
setStorageItems(items: any[]) {
localStorage.setItem('items', JSON.stringify(items));
}
getStorageItems(): any[] {
try {
return JSON.parse(localStorage.getItem('items'));
} catch(err) {
console.warn(err);
return [];
}
}
ngOnInit(): void {
this.items = this.getStorageItems();
}
在HTML中:
<tr *ngFor="let item of items">
<td>{{item.quantity}} </td>
<td>{{item.product_name }}</td>
</tr>
在调用onSubmit函数之前,不会设置项目。看起来像这样:
storageKey = 'MyDataStorageKey';
public onSubmit(thumbnail, quantity, product_name, product_price){
var data = {
thumbnail,
quantity,
product_name,
product_price
};
if (this.items instanceof Array) {
console.log("is an array");
} else {
console.log("is not an array");
data => this.items = [data];
}
this.items.push(data);
localStorage.setItem(this.storageKey, JSON.stringify(this.items));
}