首页 文章

Ionic 2和JSON Data Addition

提问于
浏览
0

我正在使用Ionic 2 Storage来保存表单数据 . 我保存这样的数据:

this.storage.set(key, JSON.stringify(formData));

我检索并尝试更新这样的数据:

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(key) {
  return this.storage.get(key);
}

所以我知道.push是针对数组而不是对象,但我不认为它有效地完成所有这些转换,因为我正在处理大型对象 .

My question is: 从存储中检索json并附加到它的最有效方法是什么?如果对象没有像数组这样的push方法,那么.parse返回一个对象是没有意义的 .

这是错误:

运行时错误未捕获(在promise中):TypeError:无法读取未定义的属性'push'TypeError:无法读取未定义的属性'push'

1 回答

  • 0

    这个错误意味着什么,此刻没有该密钥的记录 . 所以,你必须做这样的检查:

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

相关问题