#鸿蒙通关秘籍#如何实现HarmonyOS Next中Token的持久化存储与读取?

HarmonyOS
2024-11-28 15:31:07
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
LogicLion

Token的持久化可以通过HarmonyOS提供的Preferences来实现。建议在EntryAbility的onCreate生命周期函数中定义一个全局方法来获取Preferences实例,以便在应用的其他部分可以方便读取和保存Token。

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

onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
  globalThis.getPreferences = () => {
    let preferences: Promise<dataPreferences.Preferences> = dataPreferences.getPreferences(this.context, "appStore");
    return preferences;
  }
}

//utils/index.ets 中定义getToken和setToken方法
import dataPreferences from '@ohos.data.preferences';

export const getToken: Function = async () => {
  try {
    let preferences: dataPreferences.Preferences = await globalThis.getPreferences();
    return preferences.getSync('token', '');
  }
  catch (e) {
  }
  return '';
}

export const setToken: Function = async (value: string) => {
  try {
    let preferences: dataPreferences.Preferences = await globalThis.getPreferences();
    preferences.putSync('token', encodeURIComponent(value));
    await preferences.flush();
  } catch (e) {
    console.log(JSON.stringify(e), 'e');
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
分享
微博
QQ
微信
回复
2024-11-28 16:33:30


相关问题
如何实现应用数据持久存储
2902浏览 • 1回复 待解决
关于数据持久存储如何实现
1174浏览 • 2回复 待解决
HarmonyOS 持久存储方案
829浏览 • 1回复 待解决
HarmonyOS preferences无法持久存储
691浏览 • 1回复 待解决
PersistentStorage持久存储问题
1294浏览 • 0回复 待解决