【问题标题】:Pushing old items from storage into array with new items and than saving all items to storage将旧项目从存储中推送到包含新项目的数组中,而不是将所有项目保存到存储中
【发布时间】:2017-06-08 01:36:07
【问题描述】:

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

问题在于,当添加新项目时,旧项目会被取出并放入对象数组中。但是旧的项目也仍然作为对象一个例子

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');
}

组件.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);
});
}

【问题讨论】:

    标签: angular ionic-framework


    【解决方案1】:

    变量products 是数组,以防存储有它,所以将数组推送到temp 数组将是数组中的数组,而不是连续的。

    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]);
      });
    }
    

    【讨论】:

    • 谢谢!我之前试过这个,它给了我一个错误,说我无法推送到产品,但那是因为我错过了[data]
    猜你喜欢
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多