2016-09-13 57 views
0

在我们的NG启动样板app.component.ts我有这样的代码:使用Angular 2 Services来传递全局变量?

export class AppComponent {title = "Website Title"}

在适当app.component.htmltitle将包括如下:

<p>{{title}}</p>

但我想在全球范围内包括这个title变量。比方说,我的结构如下:

app.component.html app.component.ts test.component.html test.component.ts

test.component.html我想显示相同的信息。

<p>The title of this website is {{title}}</p>

{{title}}值会从我的app.component.ts导出。我将如何使用服务传递类似字符串的内容?是否值得传递一个指令呢?喜欢的东西:

<p>The title of this website is <app-test></app-test></p>

回答

1

如果必须使用全局变量,这是在整个应用程序的结构用,您可以使用共享服务,你有共享模块的地方。

你可以阅读在这里共享模块:

https://angular.io/docs/ts/latest/guide/ngmodule.html#!#shared-module

这种服务类可能看起来像这样(在本例中公共变量):

@Injectable() 
export class SharedService { 
     globalVariable = "default"; 
} 

其实,我觉得在任何应用程序中都有这样的东西并不是一个好主意。

+0

谢谢。为什么这是一个坏主意? – abrahamlinkedin

+0

在上面的例子中,你可以看到该变量是公开的。这不是一个好习惯,因为数据不是不可变的,你可以改变它的值,例如错误:) –

+0

@abrahamlinkedin,如果你没有在这个服务的构造函数中注入任何东西,'@Injectable()'装饰器不是必须的。 – rook