简体   繁体   English

Angular2(RC5)中的应用范围变量

[英]App wide variables in Angular2 (RC5)

I want to create an application wide variable accessible between various angular2 components and imported modules. 我想创建一个可以在各种angular2组件和导入的模块之间访问的应用程序范围的变量。

I have looked at dependency injection in my app.module and thought maybe I could set a class with a property in that. 我在我的app.module查看了依赖项注入,并认为也许可以在其中设置一个带有属性的类。 However, with the new angular-RC5 release, this looks like an overcomplication for what I want to do. 但是,在新的angular-RC5版本中,这似乎让我想做的事情过于复杂。

Alternatively, I thought of using a @Inputs and @Outputs to cascade the data and subscribe to changes, however, that doesn't seem to be possible between modules. 另外,我想到了使用@Inputs和@Outputs来级联数据并订阅更改,但是,在模块之间似乎不可能。

I would be really grateful for a suggestion of the easiest way of doing this. 我真的很感谢提出一个最简单的方法的建议。

In terms of my particular application, I have a navbar component which I want to show on all routes except one. 就我的特定应用而言,我有一个导航栏组件,该组件要在除一条之外的所有路径上显示。 So I have that on my app.component template, with an *NgIf condition, which I then wanted to be able to change from various child components to display the navbar, without having to embed the navbar component in all of my child modules and components (which gets tricky with components being shared between modules. Some of my routes are imported in a module. 所以我在app.component模板上使用了* NgIf条件,然后我希望能够从各种子组件更改为显示导航栏,而不必将导航栏组件嵌入到我的所有子模块和组件中(由于组件在模块之间共享而变得棘手。我的某些路由被导入到模块中。

You can create a shared service. 您可以创建共享服务。

something like that : 像这样的东西:

import { Injectable } from '@angular/core';

@Injectable()
export class GenericService {
    data:any = {};
}

and then add it to your app.module. 然后将其添加到您的app.module中。

after that you can inject it to your component and add datas on it who will be accessible from all your components. 之后,您可以将其注入到您的组件中并在其上添加数据,您可以从所有组件中访问这些数据。

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

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