公开全局变量的角度 [英] Expose global variable in angular

查看:80
本文介绍了公开全局变量的角度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道公开全局变量不是一个好习惯,但就我而言,这是必要的.我在网页上还有另一个应用程序,除了我的角度应用程序,而且这些应用程序必须访问一个全局公开的变量.

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.

我的问题是,如何在angular内部公开变量?当我像这样将其附加到 document 时: document.test ="Hello"; ,TypeScript抛出错误 Property'test'不存在键入文档".

My question is, how to expose a variable inside angular? When I'm appending it to document like this: document.test = "Hello";, the TypeScript throws an error Property 'test' does not exist on type 'Document'.

还有另一种方法吗?

推荐答案

从一般意义上讲,是的,如果您只有Angular应用程序,则不想这样做.为了回答您的问题,以便使应用程序的其他部分正常工作,您是否尝试过在文件顶部使用声明语句来防止TypeScript抱怨?

In a general sense, yeah you would not want to do that if you just have an Angular app. 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?

// import statements

declare var document;

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

此外,您还可以让TypeScript编译器将已知变量视为 any 类型,以便可以对它使用可能不知道的任何属性.为此,您只需使用 as 语法强制转换变量.最好使用TypeScript的类型检查,但是您可以通过执行此操作选择退出.

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. To do this, you simply cast the variable using the as syntax. It is better to use TypeScript's type checking, but you can opt out of it by doing this.

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

您还应该能够为这些全局属性创建一个接口,并将文档转换为该类型,以在Angular代码中利用TypeScript的类型安全性.

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.

interface GlobalDocumentProps {
    foo: string;
}

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

这篇关于公开全局变量的角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆