【问题标题】:How to take data from native storage, add to an array then add back to native storage如何从本机存储中获取数据,添加到数组然后添加回本机存储
【发布时间】:2023-03-21 08:28:01
【问题描述】:

我正在使用 ionic/cordova 构建应用程序。我需要能够扫描条形码,然后将时间戳(实现这一点)添加到设备的本机存储中。

我尝试将扫描数据添加到本机存储,但发现它只是覆盖了现有的扫描数据。然后我使用数组尝试了这个,但再次注意到如果我更改页面,当页面再次加载时数组为空,因此它将现有数据替换为新的空数组。

我“认为”我需要做的是—— 创建一个空数组 获取现有数据本机存储并添加到此阵列 将新的扫描数据添加到此阵列 然后将数组添加回本机存储。

我目前坚持的是将数据从本机存储中取出并添加到数组中。 我的代码是 -

export class ScanSession {

scans: any [];

constructor(private barcodeScanner: BarcodeScanner, private          
nativeStorage: NativeStorage) { 
 this.scans = [];   
}

ScanCode() : any{
this.barcodeScanner.scan().then((barcodeData) => {

this.nativeStorage.getItem('scans')
.then(
  data => console.log(data),
  error => console.error(error)
);

  this.scans.push(data);

let inputString = "testData";

//let ts = new Date();

if( barcodeData.text == inputString){
  //this.scans.push(ts);
  this.nativeStorage.setItem('scans', (JSON.stringify(this.scans)))
  //(JSON.stringify(this.scans)
  .then(
    () => console.log('Stored item!'),
    error => console.error('Error storing item', error)
  );
  //console.log("Success");
  //console.log(this.scans);

  //this.nativeStorage.getItem('scans')
  //.then(
  //  data => console.log(data),
  //  error => console.error(error)
  // );

} else {
  console.log("Doesnt Match");
}

}, (err) => {

});
};
}

【问题讨论】:

    标签: android arrays cordova typescript ionic-framework


    【解决方案1】:

    您使用 JSON.stringify 时缺少 JSON.parse,如果您明白我的意思,您需要取消字符串化。

    改变

     this.nativeStorage.getItem('scans')
    

     JSON.parse(this.nativeStorage.getItem('scans'))
    

    【讨论】:

    • 谢谢,但是当我进行更改时会返回错误。我在别处得到了我的代码吗?我不确定应该在代码的哪个位置使用 getItem 命令。
    • 尝试先将其添加到 var 中,如下所示: var myData= JSON.parse(this.nativeStorage.getItem('scans')); var 中有什么?注意:使用 corodva 应用程序,您可以使用 localStorage 而无需额外的层。
    • localstoage 也不是异步的,promise 会立即解决,所以不需要使用,严格来说见peterbe.com/plog/localstorage-is-fast
    • 我试过 - var myData = JSON.parse(this.nativeStorage.getItem('scans');) 返回一个错误说 - 'Promise' 类型的参数不能分配给参数输入“字符串”。
    • 在没有 then 函数的情况下尝试它,如果 nativeSrorage 尝试两个组合,请尝试使用 localStorage。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    • 2021-03-24
    • 2022-01-10
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    相关资源
    最近更新 更多