公开全局变量的角度

编程入门 行业动态 更新时间:2024-10-09 02:31:35
本文介绍了公开全局变量的角度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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;

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';

更多推荐

公开全局变量的角度

本文发布于:2023-10-30 18:39:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1543682.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:角度   全局变量

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!