简体   繁体   English

公开全局变量的角度

[英]Expose global variable in angular

I know exposing a global variable is not a good practice, but in my case its necessary. 我知道公开全局变量不是一个好习惯,但就我而言,这是必要的。 I have another applications on a web-page alongside my angular one and those must access one globally exposed variable. 我在网页上除了我的角度应用程序外还有另一个应用程序,这些应用程序必须访问一个全局公开的变量。

My question is, how to expose a variable inside angular? 我的问题是,如何在angular中公开变量? When I'm appending it to document like this: document.test = "Hello"; 当我将其附加到documentdocument.test = "Hello"; , the TypeScript throws an error Property 'test' does not exist on type 'Document'. ,则TypeScript会引发错误Property 'test' does not exist on type 'Document'.

Is there an another way of doing this? 还有另一种方法吗?

In a general sense, yeah you would not want to do that if you just have an Angular app. 从一般意义上讲,是的,如果您只有Angular应用程序,则不想这样做。 To answer your question tho so that you can get the other part of your app to work, did you try to use a declare statement at the top of your file to prevent TypeScript from complaining? 为了回答您的问题,以便使应用程序的另一部分正常工作,您是否尝试过在文件顶部使用声明语句来防止TypeScript投诉?

// import statements

declare var document;

http://blogs.microsoft.co.il/gilf/2013/07/22/quick-tip-typescript-declare-keyword/ http://blogs.microsoft.co.il/gilf/2013/07/22/quick-tip-typescript-declare-keyword/

Additionally, you can have the TypeScript compiler treat a known variable as the any type so you can use whatever properties you want on it that it may not know about. 此外,您可以让TypeScript编译器将已知变量视为any类型,以便您可以使用对其可能不了解的任何属性。 To do this, you simply cast the variable using the as syntax. 为此,您只需使用as语法强制转换变量。 It is better to use TypeScript's type checking, but you can opt out of it by doing this. 最好使用TypeScript的类型检查,但是您可以通过这样做选择退出。

(document as any).foo = 'bar';

You should also be able to create an interface for these global properties and cast the document as that type to make use of TypeScript's type safety in your Angular code. 您还应该能够为这些全局属性创建一个接口,并将文档转换为该类型,以便在Angular代码中使用TypeScript的类型安全性。

interface GlobalDocumentProps {
    foo: string;
}

(document as GlobalDocumentProps).foo = 'bar';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM