HarmonyOS dataPreferences如何持久化存储数据,重启app后被清空?

代码实现:

export class UserCache {
  //首选项
  private preferences: dataPreferences.Preferences | null = null;

  private constructor() {
  }

  private static instance: UserCache

  public static getInstance(): UserCache {
    if (!UserCache.instance) {
      UserCache.instance = new UserCache();
    }
    return UserCache.instance;
  }


  initConfig(context: Context) {
    dataPreferences.getPreferences(context, APP_STORE_PREFERENCES,
      (error: BusinessError, val: dataPreferences.Preferences) => {
        if (error) {
          return;
        }
        this.preferences = val
      })
  }

  saveLoginInfo(model: LoginModel) {
    this.saveTokenSync(model.token)
    this.saveUserNameSync(model.userName)
    this.saveUserIdSync(model.userId)
    this.saveUniqueCodeSync(model.uniqueCode)
  }

  /**
   * 同步保存token
   * @param tokenStr
   */
  saveTokenSync(tokenStr: string) {
    this.preferences?.putSync(USER_TOKEN, tokenStr)
  }

  /**
   * 同步保存token
   * @param tokenStr
   */
  saveUserIdSync(userId: string) {
    this.preferences?.putSync(USER_ID, userId)
  }

  /**
   * 同步保存userName
   * @param username
   */
  saveUserNameSync(username: string) {
    this.preferences?.putSync(USER_NAME, username)
  }

  /**
   * 同步保存uniqueCode
   * @param uniqueCode
   */
  saveUniqueCodeSync(uniqueCode: string) {
    this.preferences?.putSync(UNIQUE_CODE, uniqueCode)
  }


  /**
   * 同步获取token
   * @returns token
   */
  getTokenSync() {
    return (this.preferences?.getSync(USER_TOKEN, "") ?? "").toString()
  }

  /**
   * 同步获取userName
   * @returns
   */
  getUserNameSync() {
    return (this.preferences?.getSync(USER_NAME, "") ?? "").toString()
  }

  /**
   * 判断是否登录
   * @returns 是否登录
   */
  isLoginSync() {
    const token = (this.getTokenSync() ?? "").toString()
    console.log("isLoginSync", this.getTokenSync())
    console.log("isLoginSync", token)
    return token.length > 0
  }

  /**
   * 清除缓存信息
   */
  cleanCache() {
    this.saveUserNameSync("")
    this.saveTokenSync("")
    this.saveUserIdSync("")
    this.saveUniqueCodeSync("")
  }
}
阅读 588
1 个回答
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进