简体   繁体   中英

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). 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. Even when I go in the chrome DevTools/IndexedDB I can see only one key and value saved.

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. 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. 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 () "

PS: If it is not clear enough to you feel free to ask I am around for a while. Here is my code:

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:

    <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). JSON.parse will throw error if you attempt to parse a string as is. See more here: Why does JSON.parse("string") fail

Now based on your code you should not need JSON.parse at all:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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