I have two ionic pages 1) Menu Items 2) Your Orders In 'Menu Items' page there are list of menu items from which each menu is selected and added which is then passed to 'Yours Order' page. From 'Menu Items' page I am sending each item as a JSON object then I am trying to push it on array 'orders' which is on 'Yours Order' page. Then, I am storing that array to LocalStorage. Here, for first item it works but when I try to enter next item, going back to Menu items page, The first one gets replaced and only the latest one is stored which I actually don't want. I want to push multiple items to order page. What can be the solution??
[This is handler in "Menu Items" page from where each item is sent to 'Yours Order' page.]
handler: data => {
this.orderItem = {'tableId':this.tableId, 'menuId': menuItemData.item_id, 'menuName': menuItemData.name, 'qty': data.qty,
'rate': menuItemData.price, 'description': data.description};
this.navCtrl.push(OrderpagePage, {'orderItem':this.orderItem});
}
From here I have pushed items in localstorage.
ionViewWillEnter() {
let temp = this.navParams.get('orderItem');
if(this.localStorageService.get('order') == null){
this.orders.push(temp);
this.localStorageService.set('order', this.orders);
} else {
let length:any[] = JSON.parse(this.localStorageService.get('order'));
console.log(length)
let temp1 = length.push(temp)
this.localStorageService.add('order', temp1)
}
Array.push
returns the new length of the array, not a reference or copy of the array. As noted in another answer, add
does not exist. Also, you seem to be mixing whether the stored value is a JSON string or a javascript type. LocalStorage takes string values.
ionViewWillEnter() {
const order = this.navParams.get('orderItem');
const ordersString = this.localStorageService.get('order')
const orders = typeof ordersString === 'string'
? JSON.parse(ordersString)
: []
orders.push(order)
this.localStorageService.set('order', JSON.stringify(orders))
}