Trying to save as Object Array but keeps getting saved as Array of Array


#1

I am trying to implement an interface to make it easier to post data to my database. Before I tried to implement the interface each additional product would just get stored as an object inside the array. After trying to implement the interface the first product is an object and the rest are array of array objects

AddItem.ts

 name: string = this.navParams.get('name');
 desc: string = this.navParams.get('desc');

saveItem() {

    let newItem = {
      name: this.name,
      desc: this.desc
    };

    this.dataStorageService.save(newItem).then(() => {
      this.navCtrl.pop(Search);
    });
}

DataStorageService.ts

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

Here is what I’m trying to do now

Order.Interface.ts

export interface Order {

  name: string;
  desc: string;
}

AddItem.ts

name: string = this.navParams.get('name');
desc: string = this.navParams.get('desc');
orders = [] as Order[];

saveItem(): void {

this.orders.push({name: this.name, desc: this.desc});

this.dataStorageService.save(this.orders).then(() => {

});

DataStorageService.ts

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

#2

thanks @RezaRahmati had to change save() to

save(data): Promise<any> {

   return this.getData().then((products: any[]) => {
   if (products) {
     products = products.concat(data);
     return this.storage.set('products', products);
   }
   return this.storage.set('products', data);
   });
}

#3

You bothered to create an interface for Order. Why not do the same for Product so you can get rid of all these anys?


#4

I dont have any products they are actually just the items in Order[] so I guess I’ll change it to products: Order[]

Thanks