HarmonyOS Entry和Hsp中创建的单例失效

export class GlobalContext { 
  private constructor() { } 
  private static instance: GlobalContext; 
  private _objects = new Map<string, Object>(); 
 
  public static getContext(): GlobalContext { 
    if (!GlobalContext.instance) { 
      GlobalContext.instance = new GlobalContext(); 
    } 
    return GlobalContext.instance; 
  } 
 
  getObject(value: string): Object | undefined { 
    return this._objects.get(value); 
  } 
 
  setObject(key: string, objectClass: Object): void { 
    this._objects.set(key, objectClass); 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

在Entry 中 存值 GlobalContext.getContext().setObject(“windowStage”, windowStage)

在动态共享包中取值 let windowStage = GlobalContext.getContext().getObject(“windowStage”) as window.WindowStage 取不到

排查发现 GlobalContext.getContext() 获取到的不是一个实例,单例失效了

如何解决?

HarmonyOS
2024-08-02 11:42:35
浏览
已于2024-8-2 19:09:56修改
收藏 0
回答 1
回答 1
按赞同
/
按时间
十根玉米

目前windowStage只在entryAbility的onwindowStageCreate中获取到,然后需要用APPStorage把windowStage拿出来。示例如下:

onWindowStageCreate(windowStage: window.WindowStage): void { 
  // Main window is created, set main page for this ability 
  windowStage.loadContent('pages/Index', (err) => { 
  if (err.code) { 
   return; 
} 
}); 
AppStorage.setOrCreate('windowStage',windowStage); 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-appstorage-V5

分享
微博
QQ
微信
回复
2024-08-02 19:08:27
相关问题
hsp存在多个情况
930浏览 • 1回复 待解决
HarmonyOS 如何创建WebView组件
819浏览 • 1回复 待解决
创建换了页面后不生效问题
2955浏览 • 3回复 待解决
HarmonyOS 问题
1163浏览 • 1回复 待解决
HarmonyOS 关于问题
1310浏览 • 1回复 待解决
HarmonyOS 对象如何实现
1359浏览 • 1回复 待解决
HarmonyOS 模式不生效
1029浏览 • 1回复 待解决
关于文档说har不能用疑惑
2669浏览 • 1回复 待解决
如何获取为undefined
1351浏览 • 1回复 待解决
HarmonyOS 模式拿不到类对象
1361浏览 • 1回复 待解决
HarmonyOS 怎么实现线程安全
1098浏览 • 1回复 待解决
HarmonyOS TaskPool子线程问题
1165浏览 • 1回复 待解决
HarmonyOS navigation有模式吗
991浏览 • 1回复 待解决