加入收藏 | 设为首页 | 会员中心 | 我要投稿 天瑞地安资讯网 (https://www.52baoding.com/)- 网络、物联网络、物联安全、云安全、行业智能!
当前位置: 首页 > 服务器 > 系统 > 正文

自定义GlobalThis进行数据同步

发布时间:2024-01-07 00:34:21 所属栏目:系统 来源:DaWei
导读:   这里自定义一下GlobalThis全局对象,通过在GlobalThis对象上绑定属性/方法, 下面通过一个简单实例,全局存储context,存储属性值,存储首选项对象。  想了解更多关于开源的内容,请访

  这里自定义一下GlobalThis全局对象,通过在GlobalThis对象上绑定属性/方法, 下面通过一个简单实例,全局存储context,存储属性值,存储首选项对象。

  想了解更多关于开源的内容,请访问:

  51CTO 鸿蒙开发者社区

  https://ost.51cto.com

  1、前言

  在OpenHarmony 3.2 Release版本的配套文档,对应API能力级别为API 9 Release时,使用globalThis进行数据同步:在ArkTS引擎实例内部,globalThis是一个全局对象,可以被ArkTS引擎实例内的UIAbility组件、ExtensionAbility组件和ArkUI页面(Page)访问。但在OpenHarmony 4.0 Release版本的配套文档,对应API能力级别为API 10 Release后,就弃用了globalThis全局对象,如果我们之前的项目里有用到globalThis全局对象,而在新的API 10里不能用了,我们是可以通构造一个单例对象来处理的。这里自定义一下GlobalThis全局对象,通过在GlobalThis对象上绑定属性/方法, 下面通过一个简单实例,全局存储context,存储属性值,存储首选项对象。效果图如下:

  2、自定义GlobalThis单例对象

  复制

  import common from '@ohos.app.ability.common';

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

  // 构造单例对象

  export class GlobalThis {

  private constructor() {}

  private static instance: GlobalThis;

  // 缓存context

  private _uiContexts = new Map();

  // 缓存属性值

  private _attribute = new Map();

  // 缓存首选项

  private _preferences = new Map>();

  public static getInstance(): GlobalThis {

  if (!GlobalThis.instance) {

  GlobalThis.instance = new GlobalThis();

  }

  return GlobalThis.instance;

  }

  getContext(key: string): common.UIAbilityContext | undefined {

  return this._uiContexts.get(key);

  }

  setContext(key: string, value: common.UIAbilityContext): void {

  this._uiContexts.set(key, value);

  }

  getAttribute(key: string): string | undefined {

  return this._attribute.get(key);

  }

  setAttribute(key: string, value: string): void {

  this._attribute.set(key, value);

  }

  getPreferences(key: string): Promise | undefined {

  return this._preferences.get(key);

  }

  setPreferences(key: string, value: Promise): void {

  this._preferences.set(key, value);

  }

  // 其他需要传递的内容依此扩展

  }

  3、使用说明

  在EntryAbility.ets中导入构建的单例对象GlobalThis。

  复制

  import { GlobalThis } from '../utils/GlobalThis'; // 需要根据globalThis.ets的路径自行适配

  1.

  在onCreate中添加:

  复制

  GlobalThis.getInstance().setContext("context", this.context);

  1.

  在Page中使用:

  复制

  let context: common.UIAbilityContext | undefined = GlobalThis.getInstance().getContext("context");

  1.

  4、实现效果图Demo

  效果图实例包含两个Page, 一个自定义GlobalThis单例对象。

  在ets目录下创建utils目录,并创建GlobalThis.ets文件,代码如上面。

  首页面显示在EntryAbility.ets文件onCreate()方法设置好的属性值,context, 首选项数据库.

  onCreate()方法添加代码如下:

  复制

  import { GlobalThis } from '../utils/GlobalThis';

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

  import { BusinessError } from '@ohos.base';

  const PREFERENCES_NAME = 'nutsusPreferences';

  const KEY_APP_PRIVACY = 'nutsusKey';

  export default class EntryAbility extends UIAbility {

  export default class EntryAbility extends UIAbility {

  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {

  // 缓存context

  GlobalThis.getInstance().setContext("context", this.context);

  // 缓存作者属性值

  GlobalThis.getInstance().setAttribute("author", "狼哥");

  // 缓存组织属性值

  GlobalThis.getInstance().setAttribute("org", "坚果派");

  let preferences: Promise = dataPreferences.getPreferences(this.context, PREFERENCES_NAME);

  // 缓存首选项Promise

  GlobalThis.getInstance().setPreferences("preferences", preferences);

  preferences.then((result: dataPreferences.Preferences) => {

  // 存储文本到nutsusKey主键

  result.putSync(KEY_APP_PRIVACY, "坚果派由坚果创建,团队拥有8个华为HDE,3个HSD,以及若干其他领域的三十余位万粉博主运营。");

  console.log('xxx')

  }).catch((err: BusinessError) => {

  console.error('xx put the preferences failed, err: ' + err);

  });

  }

  }

  首页面使用GlobalThis对象,代码如下:

  导入构建GlobalThis单例对象

  复制

  import { GlobalThis } from '../utils/GlobalThis';

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

  import { BusinessError } from '@ohos.base';

  import router from '@ohos.router';

  import common from '@ohos.app.ability.common';

  const KEY_APP_PRIVACY = 'nutsusKey';

  复制

  首页面显示函数时,从GlobalThis对象获取数据

  1.

  复制

  onPageShow() {

  this.author = GlobalThis.getInstance().getAttribute("author");

  this.org = GlobalThis.getInstance().getAttribute("org");

  let context: common.UIAbilityContext | undefined = GlobalThis.getInstance().getContext("context");

  if (context != undefined) {

  this.label = context.abilityInfo.bundleName;

  }

  let preferences: Promise | undefined = GlobalThis.getInstance().getPreferences("preferences")

  if (preferences != undefined) {

  preferences.then((result: dataPreferences.Preferences) => {

  result.get(KEY_APP_PRIVACY, "").then((data) => {

  this.message = String(data);

  })

  }).catch((err: BusinessError) => {

  console.error('xx get the preferences failed, err: ' + err);

  })

  }

  }

  复制

  首页面布局代码如下:

  1.

  复制

  Column({space: 50}) {

  Text(`[${this.org}] ${this.author}`)

  .fontSize(50)

  .fontWeight(FontWeight.Bold)

  Divider()

  Text(`${this.message}`)

  .fontSize(20)

  Button('跳转下一页')

  .width('80%')

  .height(50)

  .onClick(() => {

  router.pushUrl({

  url: 'pages/Second'

  })

  })

  Text(`获取Context的bundleName: ${this.label}`)

  .width('100%')

  .margin({top: 50})

  }

  .width('100%')

  .height('100%')

  .padding(20)

  第二页面使用GlobalThis对象,代码如下:

  导入构建GlobalThis单例对象

  复制

  import { GlobalThis } from '../utils/GlobalThis';

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

  import { BusinessError } from '@ohos.base';

  import router from '@ohos.router';

  import promptAction from '@ohos.promptAction';

  const KEY_APP_PRIVACY = 'nutsusKey';

  复制

  第二页面页面加载前函数时,从GlobalThis获取数据

  1.

  复制

  @State author: string | undefined = GlobalThis.getInstance().getAttribute("author");

  @State org: string | undefined = GlobalThis.getInstance().getAttribute("org");

  @State message: string = "";

  private preferences: Promise | undefined = GlobalThis.getInstance().getPreferences("preferences")

  aboutToAppear() {

  if (this.preferences != undefined) {

  this.preferences.then((result: dataPreferences.Preferences) => {

  result.get(KEY_APP_PRIVACY, "").then((data) => {

  this.message = String(data);

  })

  }).catch((err: BusinessError) => {

  console.error('xx get the preferences failed, err: ' + err);

  })

  }

  }

  复制

  第二页面修改数据代码如下:

  1.

  复制

  onChange() {

  if (this.author != undefined) {

  GlobalThis.getInstance().setAttribute("author", this.author);

  }

  if (this.preferences != undefined) {

  this.preferences.then((result: dataPreferences.Preferences) => {

  result.putSync(KEY_APP_PRIVACY, this.message)

  }).catch((err: BusinessError) => {

  console.error('xx set the preferences failed, err: ' + err);

  })

  }

  promptAction.showToast({

  message: '修改成功^_^',

  duration: 2000

  });

  }

  复制

  第二页面布局代码如下:

  1.

  复制

  Column({space: 50}) {

  TextInput({text: this.author})

  .onChange((value) => {

  this.author = value;

  })

  Text(`[${this.org}]`)

  .fontSize(50)

  .fontWeight(FontWeight.Bold)

  TextArea({text: this.message})

  .onChange((value) => {

  this.message = value;

  })

  Row({space: 50}) {

  Button('返回')

  .width(100)

  .onClick(() => {

  router.back();

  })

  Button('修改')

  .width(100)

  .onClick(() => {

  this.onChange()

  })

  }

  .width('100%')

  .justifyContent(FlexAlign.Center)

  }

  .width('100%')

  .height('100%')

  .padding(20)

  5、总结

  虽然在OpenHarmony 4.0 Release,对应API能力级别为API 10 Release后不能直接使用globalThis全局对象,但通过自定义单例对象后,还是很方便实现属性/方法绑定,在UIAbility和Page之间、UIAbility和UIAbility之间、UIAbility和ExtensionAbility之间都可以使用自构建GlobalThis单例对象上绑定属性/方法,可以实现之间的数据同步。

(编辑:天瑞地安资讯网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章