尝试从localStorage
中检索Json字符串并向其添加新菜。它没有运行,因为它应该,有人可以帮助我。我正在使用TypeScript
。通过解析Json追加到数组
interface Dish {
id: number;
name: string;
desc: string;
price: number;
};
export class BasketService {
private BASKET: string = 'basket';
log(dish: Dish) {
var dishList: Dish = [];
if (!localStorage.getItem(this.BASKET)) {
dishList.push(dish); //push the first dish (if local storage is empty)
}
//Append an injected dish to the existing local storage.
dishList.push(JSON.parse(localStorage.getItem(this.BASKET)));
dishList.push(dish);
localStorage.setItem(this.BASKET, JSON.stringify(dishList));
}
}
预期行为:一旦盘是很好所附,那么它应该被存储在localStorage的用于进一步操作。
什么是预期的行为? –
增加了问题的预期行为。根据你的代码,应该添加 –
。但是,之前的数组结构已经毁了。 'array1.push(array2)'不符合你的期望。 'array1 = array1.concat(array2)'是你要找的 –