赞
踩
import preferences from '@ohos.data.preferences'; const STORE_NAME = "baseInfo" let context = getContext(this) let preference: preferences.Preferences class PreferenceUtil { // 初始化对象 async getPreferences() { try { preference = await preferences.getPreferences(context, STORE_NAME) } catch (err) { console.error(`error:${err}`) } } /** * 删除所有的preferences对象 */ async deletePreferences() { try { await preferences.deletePreferences(context, STORE_NAME); } catch(err) { console.error('TAG', `Failed to delete preferences, Cause: ${err}`); }; } // 写入preference数据 async putPreference(key: string, value: string) { if (!key || !value) { return } if (!preference) { await this.getPreferences(); } // 将数据保存到首选项,内存中 try { await preference.put(key, value); } catch (err) { console.error('TAG', `Failed to put value, Cause: ${err}`); } // 【数据持久化,写入文件】Store the Preference instance in the preference persistence file await preference.flush(); } /** * 获取preference对象 */ async getPreference(key: string) { if (!key) { return } let value: number | string | boolean | Array<number> | Array<string> | Array<boolean>; if (!preference) { await this.getPreferences(); } try { value = await preference.get(key, '') } catch (err) { console.error('TAG', `Failed to get value, Cause: ${err}`) } if (value === '') { return } return value; } } export default new PreferenceUtil();
import userInfoStrong from '../../utils/preferencesUtils';
// 存
userInfoStrong.putPreference('userInfo', JSON.stringify(userInfo))
// 异步获取保存的数据
userInfoStrong.getPreference('userInfo').then((res: any) => {
console.log(res, 111111111111111111111)
})
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。