HarmonyOS如何在ts中调用ets文件中的变量

在index.ets文件中获取到了应用的沙箱路径:filesDir,现在想在处理业务逻辑的ts文件中引用这个目录,请问需要用什么办法拿到这个目录。

let context = getContext(this) as common.UIAbilityContext;  
export let filesDir = context.filesDir; 

示例:

async screenshot(): Promise<string> { 
  const timestamp = Date.now(); 
  // 这里需要依赖应用所在的沙箱目录。 
  const filename = filesDir + `/data/cache/screenshot_${timestamp}.png`; 
  try { 
  let status = await this.driver.screenCapture(filename); 
  if (status == true){ 
  // 这里读取截图拿到其对应的字节并返回 
  return imageData; 
} 
else 
throw new Error("screenCapture failed."); 
} catch (error) { 
  Logger.error(TAG, `screenshot failed:${error}`); 
  throw error; 
} 
}
HarmonyOS
2024-08-27 11:45:38
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
FengTianYa

ts文件无法从ets文件中导入资源,因此无法使用import方式导入。想要在ts中调用ets中的变量,可以使用全局作用域globalThis或者AppStorage保存变量。示例如下:

// index.ets 
let context = getContext(this) as common.UIAbilityContext; 
export let filesDir: string = context.filesDir; 
// globalThis 
globalThis.filesDir = filesDir 
// AppStorage 
AppStorage.setOrCreate("filesDir", filesDir)
// xxx.ts 
// globalThis 
let filesDir = globalThis.filesDir 
// AppStorage 
let filesDir = AppStorage.get("filesDir")
分享
微博
QQ
微信
回复
2024-08-27 17:29:34
相关问题
ets文件怎么调用ts文件定义方法
2521浏览 • 1回复 待解决
eTS文件ts文件区别
1963浏览 • 1回复 待解决
如何在ets引入zlib.js?
2276浏览 • 1回复 待解决
是否会长期支持ets调用ts代码
1510浏览 • 1回复 待解决
如何在js文件引入自定义js文件
7482浏览 • 1回复 待解决
如何在HarmonyOS添加编译参数
163浏览 • 1回复 待解决