如何更改 TypeScript/Ionic 中任何文件的全局变量值?

How to change value of global variable on any files in TypeScript/Ionic?

我是 Typescript 的新手。想要一个可以在 Ionic 内的任何地方更改和检索的变量。看过一些全局变量的实现,但只找到了在其他 class/file.

上检索值的示例

基本上,我想 store/retrieve 来自 oauth2 的刷新令牌的值。这将在每次 API 调用时频繁更改,也需要检索。

有没有办法快速做到这一点?

提前致谢。

如果你真的需要使用全局作用域,那么使用 declare 语句来访问全局作用域中的变量:

declare var test: any;

class AnyThing {
    changeTest(): void {
        test = 'something';
    }
}

let at = new AnyThing();
at.changeTest();
console.log(test);

但是,您通常可以使用其他方法在应用程序中共享变量而不会污染全局范围。 Angular/Ionic 方法是创建一个服务,该服务可以注入到您可以更新或更改变量的任何地方。 Check out the Angular docs for an example of a service

另一种简单的方法是使用 localstorage 或 sessionstorage 来共享数据。

//Set the key 'test' to the value 'something'
localStorage.setItem('test', 'something');

//Retreive the key 'test'
localStorage.getItem('test');