简体   繁体   English

离子存储模块设置和获取对象而不是字符串

[英]Ionic Storage Module to set and get Object instead of string

I need to save some usernames (input) and pictures (another button not shown in the code but the logic will be the same I think) in my Ionic 3 app without classic dataBase (think I'll use the base 64 for the pictures based on the camera from the device). 我需要在没有经典数据库的Ionic 3应用程序中保存一些用户名(输入)和图片(代码中未显示另一个按钮,但逻辑与我想的一样),而没有经典的数据库(我想将base 64用于基于图片的图片)在设备上的相机上)。 Then I should retrieve them to create ion-card profile with it. 然后,我应该检索它们以使用它创建离子卡轮廓。

Actually everytime I run my loadUser() function it only retrieve me the last username but I would like to save more. 实际上,每次我运行loadUser()函数时,它只会检索到我的最后一个用户名,但我想保存更多。 Even when I go in the chrome DevTools/IndexedDB I can see only one key and value saved. 即使我进入chrome DevTools / IndexedDB,我也只能看到保存的一个keyvalue

I need to persist theses key and value just like if is a database. 我需要坚持这些键和值,就像数据库一样。

Using an input with NgModel and a 2 buttons (one to set data and one to get data) I am trying to save some username in my Ionic 3 app (without Sql Lite) but I see that the storage.set only accept string value. 使用带有NgModel和2个按钮的输入(一个用于设置数据,一个用于获取数据),我试图在Ionic 3应用程序中保存一些用户名(没有Sql Lite),但是我看到storage.set仅接受字符串值。 My idea was to use JSON.parse to retrieve the datas save in an array but the value is string at the begginning so if you have any idea let me know. 我的想法是使用JSON.parse检索保存在数组中的数据,但是在开始时值是字符串,所以如果您有任何想法请告诉我。 Bellow is the code I tried but I get an error: " core.js:1449 ERROR Error: Uncaught (in promise): SyntaxError: Unexpected token d in JSON at position 0 SyntaxError: Unexpected token d in JSON at position 0 at JSON.parse () " 贝娄是我尝试的代码,但出现错误:“ core.js:1449错误错误:未捕获(承诺):SyntaxError:JSON在位置0处出现意外的令牌d SyntaxError:JSON在JSON位置0处出现了意外的令牌d。解析()

PS: If it is not clear enough to you feel free to ask I am around for a while. PS:如果您不清楚,请随时询问我在附近。 Here is my code: 这是我的代码:

parameter.ts parameter.ts

export class ParametrePage {

   key: string = 'username';

   inputext: string;

   inputextGroup = [];

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private storage: Storage
 ) {}

  saveUser() {
  // set a key/value
     this.storage.set(this.key, this.inputext);
  }

  loadUser() {
// Or to get a key/value pair

  this.storage.get(this.key).then(val => {
  this.inputtextGroup = JSON.parse(val);
     console.log('You name is', val);
     });
    }
  }

parameter.html: parameter.html:

    <h6>Add a profilname</h6>
    <div class="form-container">
      <div class="input-container">
        <p class="diName">Name :</p>
        <ion-input [(ngModel)]="inputext" class="daInput" type="text"></ion- input>
        </div>

  <button class="charlotte-button addUser" ion-button icon-left 
  (click)="saveUser()">
      <ion-icon class="picto picto-reply"></ion-icon>
      Add a user
    </button>

    <button class="charlotte-button addUser" ion-button icon-left 
 (click)="loadUser()">
      <ion-icon class="picto picto-reply"></ion-icon>
      Load user
    </button>

In your case the value you store in the Storage is a string (inputext:string). 在您的情况下,您存储在存储中的值是一个字符串(inputext:string)。 JSON.parse will throw error if you attempt to parse a string as is. 如果您尝试按原样解析字符串,JSON.parse将引发错误。 See more here: Why does JSON.parse("string") fail 在此处查看更多信息: 为什么JSON.parse(“ string”)失败

Now based on your code you should not need JSON.parse at all: 现在,根据您的代码,您完全不需要JSON.parse:

loadUser() {
// Or to get a key/value pair
  this.storage.get(this.key).then(val => {
  this.inputtextGroup = val;
     console.log('You name is', val);
     });
  }
}

But if you say you data input eventually can be something else. 但是,如果您说您输入的数据最终可能是其他东西。 Then you can condition it a bit with try catch: 然后可以使用try catch对其进行一些调整:

loadUser() {
// Or to get a key/value pair
  this.storage.get(this.key).then(val => {
         try {
             JSON.parse(val);
         } catch(e) {
             // do here what you need since its a string
         }
             // do here what you need with parsed data
         });
    }
}

Now if there is a need to store more than one name at a time in the app. 现在,如果需要一次在应用程序中存储多个名称。 There are several "strategies" you can use: 您可以使用几种“策略”:

  1. Differentiate stored data based on the "key". 根据“键”区分存储的数据。 So the key (in key/value pair that you use to save data into Storage) should represent unique user, of course something needs to keep track of such users to be able to retrieve those: 因此,密钥(用于将数据保存到存储中的密钥/值对中)应该代表唯一的用户,当然,需要一些东西来跟踪此类用户才能检索到这些用户:
 users = ["userUniqueName1", "userUniqueName2", etc] ... this.storage.get(users[1]).then(()=>{...}) 
  1. Store data in an object and stringify it before storing: 将数据存储在对象中,并在存储之前对其进行字符串化:
 users = [ { name: "userUniqueName1", surname: "whatever" }, { name: "userUniqueName2", surname: "whatever" }, ... ] 

now before you store the object (array), you need to stringify it: 现在,在存储对象(数组)之前,需要对其进行字符串化:

storeUsers() {
    let usersStringifiedObj = JSON.stringify(this.users);
    this.storage.set("users", usersStringifiedObj);
}

retrieveUsers() {
    this.storage.get("users").then( users => {
        this.users = JSON.parse(users);
    })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM