I want to define an array of objects, then store objects within the array, however I only have one object in the array(last object), and I can't add more objects to it.
In Dataservice class
getData(){
return this.storage.get('x').then((val) => {
console.log('x',val);
});
}
async setData( Name, Code, date){
let Info=[{
Name:Name,
Code:Code,
date:date
}];
console.log(typeof(Info)); // returns object
return this.storage.set('x',JSON.stringify(Info));
}
Calling set and get methods in home page:
async loadData() {
await this.dataservice.getData();
}
async addData(name,code,date){
await this.dataservice.setData(name,code,date);
this.getData()
}
In Another function in home page:
postAPI(){
this.addData('Sara','XXX','2022/10/10');
}
Output:
x [{…}]0:
Name: "Sara"
Code: "XXX"
date: '2022/10/10'
[[Prototype]]: Object length: 1
[[Prototype]]: Array(0)
CodePudding user response:
If you want to append data to storage, you first have to get it and append to it.
async setData(data: any) {
let _tmp = await this.storage.get('x') || [] ;
_tmp.push(data);
await this.storage.set('x', _tmp);
}
CodePudding user response:
If you want all responses to be saved then while adding the data to storage, first get all existing data from storage, then add/append data to existing data and then save all data back to storage.
async setData(Name, Code, date) {
let existingData = await this.storage.get('x');
let newData = { Name:Name, Code: Code, date: date };
if (!existingData) {
existingData = [newData]
} else {
existingData.push(newData);
}
await this.storage.set('x', JSON.stringify(existingData));
}