简体   繁体   English

离子存储实现:获取并设置

[英]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. 我正在尝试了解如何从ionic Storage中获取和检索数据,由于我是新手,因此需要一些帮助。

Suppose I have line that sets the following JSON document into a storage key: 假设我有一行将以下JSON文档设置为存储密钥:

 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. 使用storage.set('persons', persons) ,我能够将JSON的值设置为离子存储的persons键。

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? 当我想更改JSON文件"id": 0002的第二项"id": 0002 ,是否应将整个JSON读取到内存中,搜索0002并进行修改,然后将其发送回新的JSON文档到离子存储中? or there is a better way? 还是有更好的方法?

Thanks in advance. 提前致谢。

Ionic Storage is based on localForage library and it is a simple key/value storage. 离子存储基于localForage库,它是一个简单的键/值存储。

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]) storage.set(“ persons_person00”,人员[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 同样在后一种方法中,您可能需要使用.forEach存储方法,具体取决于您在初始化等过程中“全部读取”的需要

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

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

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