简体   繁体   English

如何在 Angular 中创建全局变量?

[英]How can i make global variable in Angular?

During my testing in angular i use a lot of console logs.在我对 angular 进行测试期间,我使用了很多控制台日志。 I don't want to repeat my self.我不想重复我自己。 For example if i write in the class in some angular component.例如,如果我在某些 angular 组件中写入 class。

const c = console;
c.log("something");

it will work.它会起作用的。

How can i make this c variable global, so everywhere where i write c.log it will know that this c is for this console and i will not need to write in each component in each class How can i make this c variable global, so everywhere where i write c.log it will know that this c is for this console and i will not need to write in each component in each class

const c = console;

Albeit this is anti-pattern and you can really just use a service and inject it to your components as a dependency (preferred), but if you really want to do it via global variable you can do so by attaching your function / object to the global "window" object.尽管这是反模式,您实际上可以只使用服务并将其作为依赖项注入到您的组件中(首选),但如果您真的想通过全局变量执行此操作,您可以通过将 function / object 附加到全局“窗口”object。

Every browser has a global window object available.每个浏览器都有一个全局 window object 可用。

At the top of your main.ts file you can add this line:在 main.ts 文件的顶部,您可以添加以下行:

declare var window: any;
window.c = console

Basically what it does is that it attaches the console object to the "c" field of window object.基本上它所做的是将控制台 object 附加到 window object 的“c”字段。 You can just use it then anywhere globally:您可以在全球任何地方使用它:

c.log("Hello World")

Do note that I added it in the main.ts file because that's where an angular application gets started.请注意,我在 main.ts 文件中添加了它,因为这是 angular 应用程序开始的地方。 But you can add these anywhere you need (but the instantiation time will differ on where you have added it into) and it should be available globally.但是你可以在任何你需要的地方添加它们(但实例化时间会因你添加它的位置而异)并且它应该是全局可用的。

For anything that you want to access between multiple components in angular, angular services are recommended.对于您想要在 angular 中的多个组件之间访问的任何内容,建议使用 angular 服务。 see here https://angular.io/tutorial/toh-pt4 Essentially you can build a class with any functionality you want, then import this class into any component and use anything within that class. see here https://angular.io/tutorial/toh-pt4 Essentially you can build a class with any functionality you want, then import this class into any component and use anything within that class. You could create a logging service to log any debug errors, however I would not suggestcreating a class just for basic console logging.您可以创建一个日志服务来记录任何调试错误,但我不建议创建一个 class 仅用于基本控制台日志记录。

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

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