简体   繁体   中英

ionic Storage implemenation: get and set

I am trying to understand how to get and retrieve data from ionic Storage and I need some help since I am new at this.

Suppose I have line that sets the following JSON document into a storage key:

 person = [
     { "id": "0001", 1:"name", 2:"gender", 3: "age":"5"},
     { "id": "0002", 1:"name", 2:"gender", 3: "age":"5"}
    ]

using storage.set('persons', persons) , I am able to set the values of the JSON to the persons key of ionic storage.

When I want to change the second item of the JSON file "id": 0002 , should I read the whole JSON to memory, search for 0002 and modify then send back to a fresh JSON document to ionic storage? or there is a better way?

Thanks in advance.

Ionic Storage is based on localForage library and it is a simple key/value storage.

Based on your example you have 2 options with this Storage:

  1. If overall size of person(s) object is relatively small you can indeed store whole object as one value. This means if you need to change an item inside object (or array) - you have to get full object (containing all persons data), change the item, persist (set) it again as a whole object

  2. If you expect to do a lot of these operations and size of data will grow you can approach this by “splitting” your object and using differentiated keys for each “person” item as value:

storage.set(“persons_person00”, persons[0])

This approach requires you to think carefully about your keys naming conventions as you will want to be very consistent with names.

Also in the latter approach you may need to use .forEach method of Storage depending on your needs to “read all” during initialization etc

我认为,最好的方法是滚动数组,更改特定项目,然后使用此更改设置新的obj。

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