PersistentStorage存储数据后再次打开app时取出数据的数据为undefined
用户登录页面,登录成功时将用户一些基础信息存储在本地,下次打开app时可以自动登录校验,但是再次打开App时 AppStorage.get取出的数据都为undefined可看截图,查看沙盒文件中数据是存在的可看截图。另外调试发现,在App当前进程中存储后,然后去读取,数据是能正常取到的。
代码如下:
import { AccountModel } from '../models/user/AccountModel'
import { isStringEmpty } from '../utils/JudgeUtils';
import { LoginApi } from '../network/apis/LoginApi'
import { Logger } from '../utils/Logger'
import { LoginError } from '../network/HttpError'
import { AppConstants } from '../constants/AppConstants'
const TAG: string = 'DanDan-login'
AppStorage.link('uid');
AppStorage.link('token');
AppStorage.link('userSig');
AppStorage.link('phone');
export class AccountCenter {
private static instance: AccountCenter;
accountModel: AccountModel = new AccountModel();
public static getInstance(): AccountCenter {
if (!AccountCenter.instance) {
AccountCenter.instance = new AccountCenter();
const uid: string | undefined = AppStorage.get('uid');
const token: string | undefined = AppStorage.get('token');
const userSig: string | undefined = AppStorage.get('userSig');
const phone: string | undefined = AppStorage.get('phone');
const model: AccountModel = new AccountModel();
model.uid = uid ? uid : '';
model.token = token ? token : '';
model.userSig = userSig ? userSig : '';
model.phone = phone ? phone : '';
AccountCenter.instance.accountModel = model;
if (!isStringEmpty(model.uid) && !isStringEmpty(model.token)) {
AppStorage.setOrCreate('isLogin', true);
} else {
AppStorage.setOrCreate('isLogin', false);
}
}
return AccountCenter.instance
}
public static setInstance(account: AccountModel) {
AccountCenter.instance.accountModel = account;
// 本地化缓存里存储
PersistentStorage.persistProp('uid', account.uid);
PersistentStorage.persistProp('token', account.token);
PersistentStorage.persistProp('userSig', account.userSig);
PersistentStorage.persistProp('phone', account.phone);
if (!isStringEmpty(account.uid) && !isStringEmpty(account.token)) {
AppStorage.setOrCreate('isLogin', true);
} else {
AppStorage.setOrCreate('isLogin', false);
}
}
logInWithPhone(params: Record<string, Object>): Promise<AccountModel> {
return new Promise((resolve, reject) => {
LoginApi.userLogin(params).then((data: AccountModel) => {
AccountCenter.setInstance(data)
Logger.info(TAG, `登录接口返回信息:${data}`)
resolve(data);
}).catch((error: Error) => {
//判断异常是否 LoginError
if (error instanceof LoginError) {
const LoginError = error as LoginError;
if (LoginError.code == AppConstants.TRUSTED_DEVICES_ERROR_COD) {
this.logout();
reject(LoginError);
} else if (LoginError.code == AppConstants.DELETE_ACCOUNT_ERROR_COD) {
} else {
}
}
reject(error);
})
})
}
}
PersistentStorage必须在当前进程中读取。PersistentStorage是应用程序中的可选单例对象,用于持久化存储选定的AppStorage属性,确保这些属性在应用程序重新启动时的值与应用程序关闭时的值相同 。所有属性访问都是通过AppStorage的访问,AppStorage中的更改会自动同步到PersistentStorage 。
因此,PersistentStorage的读取和写入操作都必须在当前进程中进行。
参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-persiststorage-V5