代码实现:
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("")
}
}
需要持久化时可以使用flush接口将内存中的数据写入持久化文件中。参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/data-persistence-by-preferences-V5
确认ide的相关设置:点击IDE页面菜单栏run-\>Edit Confingurations。确定Keep Application Data是否勾选。