代码之家  ›  专栏  ›  技术社区  ›  pren

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

  •  1
  • pren  · 技术社区  · 7 年前

    我不熟悉打字。想有一个变量,可以改变和检索任何地方在离子。研究了一些全局变量实现,但只找到了检索其他类/文件上的值的示例。

    基本上,我想从oauth2存储/检索刷新令牌的值。每次API调用都会频繁更改,并且也需要检索。

    1 回复  |  直到 7 年前
        1
  •  0
  •   hagner    7 年前

    如果确实需要使用全局范围,请使用declare语句访问全局范围中的变量:

    declare var test: any;
    
    class AnyThing {
        changeTest(): void {
            test = 'something';
        }
    }
    
    let at = new AnyThing();
    at.changeTest();
    console.log(test);
    

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

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