一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

服務器資訊|IT/互聯網|云計算|區塊鏈|軟件資訊|操作系統|手機數碼|百科知識|免費資源|頭條新聞|

服務器之家 - 新聞資訊 - 操作系統 - 自定義GlobalThis進行數據同步

自定義GlobalThis進行數據同步

2024-01-05 17:02未知服務器之家 操作系統

想了解更多關于開源的內容,請訪問: 本站 鴻蒙開發者社區 1、前言 在OpenHarmony 3.2 Release版本的配套文檔,對應API能力級別為API 9 Release時,使用globalThis進行數據同步:在ArkTS引擎實例內部,globalThis是一個全局對象,可以被ArkTS引

自定義GlobalThis進行數據同步

想了解更多關于開源的內容,請訪問:

本站 鴻蒙開發者社區

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,存儲屬性值,存儲首選項對象。效果圖如下:

自定義GlobalThis進行數據同步

自定義GlobalThis進行數據同步


自定義GlobalThis進行數據同步

自定義GlobalThis進行數據同步

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<string, common.UIAbilityContext>();
  // 緩存屬性值
  private _attribute = new Map<string, string>();
  // 緩存首選項
  private _preferences = new Map<string, Promise<dataPreferences.Preferences>>();

  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<dataPreferences.Preferences> | undefined {
    return this._preferences.get(key);
  }

  setPreferences(key: string, value: Promise<dataPreferences.Preferences>): void {
    this._preferences.set(key, value);
  }

  // 其他需要傳遞的內容依此擴展
}

3、使用說明

在EntryAbility.ets中導入構建的單例對象GlobalThis。

import { GlobalThis } from '../utils/GlobalThis'; // 需要根據globalThis.ets的路徑自行適配

在onCreate中添加:

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

在Page中使用:

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

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.Preferences> = 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對象獲取數據
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<dataPreferences.Preferences> | 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);
        })
    }
  }
首頁面布局代碼如下:
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獲取數據
@State author: string | undefined = GlobalThis.getInstance().getAttribute("author");
  @State org: string | undefined = GlobalThis.getInstance().getAttribute("org");
  @State message: string = "";
  private preferences: Promise<dataPreferences.Preferences> | 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);
      })
    }
  }
第二頁面修改數據代碼如下:
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
    });
  }
第二頁面布局代碼如下:
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單例對象上綁定屬性/方法,可以實現之間的數據同步。

想了解更多關于開源的內容,請訪問:

本站 鴻蒙開發者社區

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 久久精品一卡二卡三卡四卡视频版 | 亚洲成在人网站天堂一区二区 | 亚洲精品AV无码喷奶水糖心 | 欧美特黄特色aaa大片免费看 | 暖暖日本高清 | 日韩成人精品在线 | 四虎黄色影视库 | 四大美女思春艳史片 | 亚洲天堂网站 | 黄德维| 日本搜子同屋的日子2国语 日本爽p大片免费观看 | 美女用手扒自己下部 | 韩国情事伦理片观看地址 | 热热99| 四虎成人国产精品视频 | avtt天堂网 手机资源 | a级免费观看 | 女子监狱第二季在线观看免费完整版 | 日韩亚洲欧美综合一区二区三区 | 小SAO货叫大声点妓女 | 亚洲大爷操 | 欧美一区a | 久久99re热在线播放7 | 石原莉奈adn093店长未婚妻 | 我与肥熟老妇的性事 | 青草免费在线 | 激情亚洲 | www.俺去| 狠狠色综合久久婷婷 | 天堂成人在线视频 | 成人免费体验区福利云点播 | 国产精品网站在线观看 | 久久不射网| 吃瓜视频在线观看 | 精品一久久香蕉国产线看观 | 男人使劲躁女人小视频 | 丝瓜视频在线观看污 | 闺蜜调教我做她的脚奴 | 爆操女友 | 亚洲AV无码偷拍在线观看 | 国产女主播在线播放一区二区 |