简体   繁体   English

Angular服务全局注入

[英]Angular service global injection

Is there a way to access a field of a service without injecting the service into every component? 有没有一种方法可以访问服务的某个领域而不将服务注入到每个组件中? or equivalently: does some concept of 'global' service exist in Angular 6? 或等效地:Angular 6中是否存在一些“全局”服务的概念?

My use case is as follows: Text labels for fields are retrieved at application startup by a service called ConfigurationManagementService. 我的用例如下:字段的文本标签在应用程序启动时由称为ConfigurationManagementService的服务检索。 This service has an observable field CurrentApplicationContext$, which has an object field ApplicationConfiguration which has a object field Label. 该服务具有一个可观察字段CurrentApplicationContext $,该对象包含一个对象字段ApplicationConfiguration和一个对象字段Label。 (this has to do with the way the backend has been set up). (这与后端的设置方式有关)。

Now: to use the labels in a view of a component, I have to inject ConfigurationManagementService (here as ConfigurationManagement) into every component and then subscribe to it (luckily I can use the direct async pipe method), like this: 现在:要在组件视图中使用标签,我必须将ConfigurationManagementService(在此称为ConfigurationManagement)注入每个组件,然后订阅它(幸运的是,我可以使用直接异步管道方法),如下所示:

<button mat-raised-button color="primary">
<mat-icon">add_shopping_cart</mat-icon> 
{{ (ConfigurationManagement.CurrentApplicationContext$ | async)?.ApplicationConfiguration?.Label['Buy'] }}
</button>

My question is: is there another shorter way of accomplishing this? 我的问题是:还有其他更短的方法来实现这一目标吗? Because this is a very time-consuming and tedious task if you execute it as mentioned for every component and every text field in the application. 因为如果按照应用程序中每个组件和每个文本字段的说明执行它,这是一项非常耗时且繁琐的任务。

Thanks! 谢谢!

将数据传递到localStorage.setItem('itemName',value) ,例如localStorage.setItem('itemName',value)或将其设置为cookie并在组件构造函数中访问它们,然后从localstorage / cookie检索数据,则无需订阅和依赖注入。但是您必须获取应用加载中的所有数据。

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

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