HarmonyOS 登录信息如何本地持久化,下次运行或者debug的时候还在

使用Preferences存储用户数据,下次运行的时候又取不到,应该怎么本地持久化一下?

static async getPreference(): Promise<dataPreferences.Preferences> {
  return await dataPreferences.getPreferences(getContext(), 'Preferences');
}

/**
 * 存
 * @param key
 * @param value
 */
static async putValue(key: string, value: string) {

  let preferences = await PreferenceUtil.getPreference();
  preferences.put(key, value);
}
HarmonyOS
2024-12-25 11:40:04
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
put_get

存储和取出首选项可参考demo:

import dataPreferences from '@ohos.data.preferences';

@Entry
@Component
struct Index {
  preferences: dataPreferences.Preferences | null = null;

  async writeModel<T>(key: string, value?: T) {
    if (this.preferences == null) {
      await this.getPreferences()
    }
    try {
      this.preferences?.putSync(key, JSON.stringify(value))
    } catch (e) {
      console.error('my_preference', 'Failed to write value, cause:' + e)
    }
    await this.preferences?.flush()
  }

  async getPreferences() {
    try {
      // let dataPreferences;
      this.preferences = await dataPreferences.getPreferences(getContext(), 'my_preference')
    } catch (e) {
      console.info('my_preference', 'Failed to get preferences, cause:' + JSON.stringify(e))
    }
  }

  async getKey(value: string) {
    if (this.preferences == null) {
      await this.getPreferences()
    }
    try {
      console.log('获取到的值+++++++++++:' + this.preferences?.getSync(value, 'string') + '')

    } catch (e) {
      console.error('my_preference', 'Failed to write value, cause:' + e)
    }
  }

  aboutToAppear(): void {
    this.getKey("name")

  }

  build() {
    Button('首选项存储').width(100).height(100)
      .onClick(() => {
        this.writeModel("name", "tom")
      })
  }
}

或者参考如下链接:https://developer.huawei.com/consumer/cn/codelabsPortal/carddetails/tutorials_NEXT-Preferences

分享
微博
QQ
微信
回复
2024-12-25 13:44:15
相关问题
HarmonyOS 元服务本地持久存储
70浏览 • 1回复 待解决
HarmonyOS 数据持久demo
181浏览 • 1回复 待解决
http 请求 如何cookie持久?
2227浏览 • 1回复 待解决
HarmonyOS preferences无法持久存储
262浏览 • 1回复 待解决
HarmonyOS 持久存储方案
483浏览 • 1回复 待解决
数据持久遇到各种问题
466浏览 • 1回复 待解决
HarmonyOS 如何进行数据持久
517浏览 • 1回复 待解决
关于数据持久存储要如何实现
808浏览 • 2回复 待解决
卡片开发中如何实现数据持久
2418浏览 • 1回复 待解决
如何实现应用数据持久存储
2499浏览 • 1回复 待解决
数据持久方式有哪些?
1287浏览 • 1回复 待解决
PersistentStorage持久存储问题
840浏览 • 0回复 待解决