如果我问了一个简单的问题,我很抱歉,因为我是打字稿的初学者。
我需要在 src/test 等目录中跨应用程序共享变量...我的变量将被声明到 file1 中并从 file2 更新它们的值,并且可以通过其 get 方法在整个应用程序中访问。
例如
文件1(SysParam.ts)
export class SysParam {
private static _domain: string;
private static _env: string;
public static get domain(): string {
return SysParam ._domain;
}
public static set domain(value: string) {
SysParam ._domain = value;
}
public static get env(): string {
return SysParam ._env;
}
public static set env(value: string) {
SysParam ._env = value;
}
}
文件2(setup.ts)
async function startUp() {
//some database calls.
SysParam.domain=result.recordset[0].domain;
SysParam.env=result.recordset[0].env;
console.log("this is my domain from setupfile: " +SysParam.domain)
}
文件3(示例.ts)
console.log("this is my domain from examplefile: " +SysParam.domain)
我还确保安装程序首先运行/程序的首字母,因此每次都应该显示变量值,并且在 file2 的结果中我确实得到了控制台日志,但在 file3 中我没有定义。
this is my domain from setupfile: xyz.com
this is my domain from examplefile: undefined
注意 我无法在这里使用 .env,因为我的变量需要根据需要一次又一次地更新。另外,我不想每次都对同一条记录进行数据库调用。
第二我尝试使用 global.d.ts 但也不起作用,因为它只是用于声明变量而不是分配它们的值,并且观察到了与上述相同的行为。
我已经在 JAVA 中实现了同样的目标,它运行良好,并且我的所有变量都保持其值,直到我的程序结束。但我在 js/typescript 中感到困惑。
有人可以指导我完整的实施指南吗?
直接回答你问的问题 - 几乎所有语言都支持全局变量,并且 TS 在这方面没有什么不同 -
但是 - 拥有全局变量通常不是解决方案,您可能只想简单地导出类并在需要的地方导入它。类是通过 TS 中的 ref 传递的,因此在更新类时,它也会“更新”ref。