Ionic 2和JSON Data Addition [英] Ionic 2 and JSON Data Addition
问题描述
我正在使用Ionic 2 Storage来保存表单数据。我保存这样的数据:
I am working with Ionic 2 Storage to persist form data. I save the data like this:
this.storage.set(key, JSON.stringify(formData));
我检索并尝试更新这样的数据:
And I retrieve and attempt to update the data like this:
this.getReport(key).then((report) => {
var objReport = JSON.parse(report);
objReport.push(data); //this is the problem
this.storage.set(pk, JSON.stringify(objReport));
});
getReport就是这样:
getReport is just this:
getReport(key) {
return this.storage.get(key);
}
所以我知道.push是针对数组而不是对象,但我不知道因为我正在处理大型物品,所以认为进行所有这些转换是有效的。
So I know that .push is for arrays and not objects, but I don't think its efficient to do all this conversions because I am dealing with large objects.
我的问题是:最有效的方法是什么从存储中检索json并附加到它?如果对象没有像数组这样的推送方法,则.parse返回一个对象是没有意义的。
My question is: what is the most efficient way to retrieve json from storage and append to it? It makes no sense to me that .parse returns an object if objects do not have a push method like arrays.
这是错误:
运行时错误未捕获(在承诺中):TypeError:无法读取属性
'timp'of undefined TypeError:无法读取
的属性'push' undefined
Runtime Error Uncaught (in promise): TypeError: Cannot read property 'push' of undefined TypeError: Cannot read property 'push' of undefined
推荐答案
这个错误的含义是,该密钥没有记录时刻。
所以,你必须做这样的检查:
what this error means is that, there are no records for that key at this moment. So, you would have to do a check like this :
this.getReport(key).then((report) => {
var objReport = [];//initialise empty Array
if(report){ //if there is a record in that key location
objReport = JSON.parse(report); //parse the record & overwrite objReport
}
objReport.push(data); //Now this push will happen regardless of report or not
this.storage.set(pk, JSON.stringify(objReport));
});
这篇关于Ionic 2和JSON Data Addition的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!