目录

HarmonyOS使用本地存储dataPreferences

HarmonyOS使用本地存储dataPreferences

在HarmonyOS中使用类似与浏览器的localStorage.

官方链接:

1、封装

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

let context = getContext(this);
let preference: dataPreferences.Preferences;
let preferenceTemp: dataPreferences.Preferences;

/**
 * Preference model.
 *
 * @param fruitData Fruit data.
 */
class PreferenceModel {
  /**
   * Read the specified Preferences persistence file and load the data into the Preferences instance.
   */
  async getPreferencesFromStorage(db_name: string) {
    try {
      preference = await dataPreferences.getPreferences(context, db_name);
    } catch (err) {
    }
  }

  /**
   * 删除本地存储
   * Deletes the specified Preferences persistence file from memory and removes the Preferences instance.
   */
  async deletePreferences(db_name: string) {
    try {
      await dataPreferences.deletePreferences(context, db_name);
    } catch(err) {
    };
    preference = preferenceTemp;
  }

  /**
   * Save the data to the Preferences.
   * 持久化存储
   * @param fruit Fruit data.
   */
  async putPreference(data: any, db_name: string, key: string) {
    if (!preference) {
      await this.getPreferencesFromStorage(db_name);
    }
    // The fruit name and fruit quantity data entered by the user are saved to the cached Preference instance.
    try {
      if (typeof data === 'object' && data !== null) {
        await preference.put(key, JSON.stringify(data));
      } else {
        await preference.put(key, data);
      }
    } catch (err) {
    }
    await preference.flush();
  }

  /**
   * 取数据
   * Get preference data.
   */
  async getPreference(db_name: string, key: string) {
    let storage;
    if (!preference) {
      await this.getPreferencesFromStorage(db_name);
    }
    try {
      storage = (await preference.get(key, ''));
    } catch (err) {
    }
    // If the data is empty, a message is displayed indicating that data needs to be written.
    if (!storage) {
      return '';
    }
    return storage;
  }

  /**
   * write data.
   * 存数据
   * @param fruit  Fruit data.
   */
  writeData(data: any, db_name: string, key: string) {
    // The data is inserted into the preferences database if it is not empty.
    this.putPreference(data, db_name, key);
    console.log(`${db_name}-${key}---writeData成功`)
  }

  /**
   * Process the data obtained from the database.
   */
  async getData(db_name: string, key: string) {
    return await this.getPreference(db_name, key);
  }

  /**
   * Popup window prompt message.
   *
   * @param message Prompt message.
   */
  showToastMessage(message: Resource) {
    promptAction.showToast({
      message: message,
      duration: 3000
    });
  };
}

export default new PreferenceModel();

2、存数据

import PreferenceModel from '../mode/PreferenceModel';
PreferenceModel.writeData('存入的数据', 'userInfo', 'user')

3、取数据

import PreferenceModel from '../mode/PreferenceModel';
const user  = await PreferenceModel.getPreference('userInfo', 'user')

注意事项:

官方说的:数据存储形式为键值对,键的类型为字符串型,值的存储数据类型包括数字型、字符型、布尔型以及这3种类型的数组类型。

如果你存的是对象,那么会自动转换为json字符串。所以在用的时候,需要JSON.parse()

上一章:

下一章: