使用新项目将旧项目从存储推送到阵列,而不是将所有项目保存到存储

时间:2017-06-07 17:20:50

标签: angular ionic-framework

我有一个类似购物车的应用。用户搜索产品并可将其添加到购物车。添加后,他们可以结帐或返回并添加更多项目。

问题是,当添加新项目时,旧项目将被采集并放入对象数组中。然而,旧项目仍然作为对象示例

Object1
Object2
Array[Object1, Object2]
Object3

[Object, Object, Array(2), Object]

如果我添加另一个项目,它将变为

[Object1, Object,2 Array(2), Object3, Array(4), Object4]

我做错了什么?

dataStorage.ts

temp = [];
temp2 = [];

// How data is saved 
save(data): Promise<any> {
  return this.getData().then((products: any[]) => {
    if (products) {
      //this.temp = products;
      this.temp.push(products, data);
      console.log(this.temp);
      return this.storage.set('products', this.temp);
    }
    return this.storage.set('products', data);
  });
}

//如何返回数据

getData() {
  return this.storage.get('products');
}

component.ts

// they click on an add button that calls this 
saveItem() {

let newItem = {
  prodName: this.prodName,
  prodDesc: this.prodDesc
};

this.dataService.save(newItem).then(()=>{
  this.navCtrl.pop(SearchProducts);
});
}

1 个答案:

答案 0 :(得分:1)

变量products是数组,以防存储有它,所以push数组到temp数组将是数组中的数组,而不是concat。

temp = [];
temp2 = [];

// How data is saved 
save(data): Promise<any> {
  return this.getData().then((products: any[]) => {
    if (products) {
      products.push(data);
      return this.storage.set('products', products);
    }
    return this.storage.set('products', [data]);
  });
}