1.1K Star 6.2K Fork 5.1K

OpenHarmony / docs

 / 详情

[问题咨询]: 多模块多ability下如何共享持久化数据

待办的
创建于  
2024-04-26 14:39

问题描述

import distributedKVStore from '@ohos.data.distributedKVStore';
import common from '@ohos.app.ability.common';
import { BaseStore } from './BaseStore.interface';
import { KVStoreConstant } from '@yunzai/core'
import { BusinessError } from '@ohos.base';


export class KVManagerStore implements BaseStore {
  private kvManager: distributedKVStore.KVManager | undefined = undefined;
  private kvStore: distributedKVStore.SingleKVStore | undefined = undefined;

  constructor(ctx: common.Context, securityLevel: distributedKVStore.SecurityLevel = distributedKVStore.SecurityLevel.S2) {
    const options: distributedKVStore.Options = {
      createIfMissing: true,
      encrypt: true,
      backup: false,
      autoSync: true,
      kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
      securityLevel: securityLevel
    }
    const config: distributedKVStore.KVManagerConfig = {
      context: ctx.getApplicationContext(),
      bundleName: "com.yunzainfo.openharmony.primaryapp",
    }
    this.kvManager = distributedKVStore.createKVManager(config);
    this.kvManager.getKVStore<distributedKVStore.SingleKVStore>(KVStoreConstant.STORE_ID, options, (err, store: distributedKVStore.SingleKVStore) => {
      if (err) {
        console.log("------------------------KV STORE ERROR--------------------------")
        console.error(`Fail to get KVStore. Code:${err.code},message:${err.message}`);
        return;
      }
      console.log("------------------------KV STORE SUCCESS--------------------------")
      console.info('Succeeded in getting KVStore.');
      this.kvStore = store;
    });
  }

  async get<T>(key: string): Promise<T | undefined> {
    if (!this.kvStore) return undefined
    try {
      const data = await this.kvStore.get(key)
      if (typeof data == 'string') {
        return JSON.parse(data) as T
      }
    } catch (e) {
      let error = e as BusinessError;
      if (error.code === 15100004) {
        return undefined
      }
    }
    return undefined
  }

  async set<T>(key: string, data: T): Promise<void> {
    if (!this.kvStore) return
    const json = JSON.stringify(data);
    await this.kvStore.put(key, json)
  }

  async remove(key: string): Promise<void> {
    if (!this.kvStore) return
    await this.kvStore.delete(key)
  }
}

当我尝试跳转

  this.context.startAbility({
      deviceId: "",
      bundleName: "com.yunzainfo.openharmony.primaryapp",
      moduleName: "oauth",
      abilityName: "OauthAbility",
      parameters: {
        callback: "pages/Index"
      }
    })

在跳转到的Ability中获取KVStore中的书局时,undefined

评论 (2)

sajdflizxcv 创建了任务
sajdflizxcv 添加了
 
question
标签
展开全部操作日志

感谢提交Issue!关于Issue的交互操作,请访问OpenHarmony社区支持命令清单。如果有问题,请联系 @NEEN @zengyawen @时睿 @Peter_1988 。如果需要调整订阅PR、Issue的变更状态,请访问链接

Thanks for submitting the issue. For more commands, please visit OpenHarmony Command List. If you have any questions, please refer to committer @NEEN @zengyawen @时睿 @Peter_1988 for help. If you need to change the subscription of a Pull Request or Issue, please visit the link.

openharmony_ci 添加了
 
waiting_for_assign
标签
import distributedKVStore from '@ohos.data.distributedKVStore';
import common from '@ohos.app.ability.common';
import { BaseStore } from './BaseStore.interface';
import { KVStoreConstant, logger } from '@yunzai/core'
import { BusinessError } from '@ohos.base';

const TAG = "KVManagerStore.ets"

export class KVManagerStore implements BaseStore {
  private kvManager: distributedKVStore.KVManager | undefined = undefined;
  private config: distributedKVStore.KVManagerConfig = {
    bundleName: "com.yunzainfo.openharmony.primaryapp",
    context: getContext(this)
  }
  private options: distributedKVStore.Options = {
    createIfMissing: true,
    encrypt: true,
    backup: false,
    autoSync: true,
    kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
    securityLevel: distributedKVStore.SecurityLevel.S2
  }

  constructor(ctx: common.Context) {
    logger.debug(TAG, "init kvStore")
    if (ctx.getApplicationContext() !== undefined && ctx.getApplicationContext() !== null) {
      logger.debug(TAG, "ctx has application context")
      this.config = {
        context: ctx.getApplicationContext(),
        bundleName: "com.yunzainfo.openharmony.primaryapp"
      }
    } else {
      logger.debug(TAG, "ctx hasn't application context")
      this.config = {
        context: ctx,
        bundleName: "com.yunzainfo.openharmony.primaryapp"
      }
    }
    this.kvManager = distributedKVStore.createKVManager(this.config);
    logger.debug(TAG, "kv store init over")
  }

  connectStore(): Promise<distributedKVStore.SingleKVStore> {
    return new Promise((resolve, reject) => {
      if (!this.kvManager) return
      this.kvManager.getKVStore<distributedKVStore.SingleKVStore>(KVStoreConstant.STORE_ID, this.options, (err, store: distributedKVStore.SingleKVStore) => {
        const isNull = (store === undefined || store === null)
        logger.debug(TAG, "connect kv store", isNull ? "null" : "not null")
        if (err) {
          logger.debug(TAG, "connect kv store error", err.message)
          reject(err)
        }
        logger.debug(TAG, "connect kv store success", JSON.stringify(store))
        resolve(store)
      });
    })
  }

  get<T>(key: string): Promise<T | undefined> {
    logger.debug(TAG, "use kv store get", key)
    return new Promise((resolve, reject) => {
      this.connectStore().then(store => {
        store.get(key).then((data) => {
          logger.debug(TAG, "use kv store get value is", data as string)
          resolve(JSON.parse(data as string) as T)
        }).catch((e: BusinessError) => {
          logger.debug(TAG, "use kv store get value error", e.message)
          if (e.code === 15100004) {
            resolve(undefined)
          } else {
            reject(e)
          }
        })
      })
    })
  }

  set<T>(key: string, data: T): Promise<void> {
    logger.debug(TAG, "use kv store set value", key, JSON.stringify(data))
    return new Promise((resolve, reject) => {
      this.connectStore().then(store => {
        const json = JSON.stringify(data);
        store.put(key, json).then(() => {
          logger.debug(TAG, "use kv store set value success")
          resolve()
        }).catch((e: BusinessError) => {
          logger.debug(TAG, "use kv store set value error", e.message)
          reject(e)
        })
      })
    })
  }

  remove(key: string): Promise<void> {
    logger.debug(TAG, "use kv store remove value", key)
    return new Promise((resolve, reject) => {
      this.connectStore().then(store => store.delete(key).then(() => {
        logger.debug(TAG, "use kv store remove value success")
        resolve()
      })).catch((e: BusinessError) => {
        logger.debug(TAG, "use kv store remove value error")
        reject(e)
      })
    })
  }
}

重新封装后解决问题

登录 后才可以发表评论

状态
负责人
项目
里程碑
Pull Requests
关联的 Pull Requests 被合并后可能会关闭此 issue
分支
开始日期   -   截止日期
-
置顶选项
优先级
预计工期 (小时)
参与者(2)
7387629 openharmony ci 1656582662 5208265 devcui 1616340460
其他
1
https://gitee.com/openharmony/docs.git
git@gitee.com:openharmony/docs.git
openharmony
docs
docs

搜索帮助

53164aa7 5694891 3bd8fe86 5694891