使用Angular 2服务传递全局变量?

时间:2016-09-13 20:04:02

标签: angular

在我们的NG启动器样板 app.component.ts 中,我有以下代码:

export class AppComponent {title = "Website Title"}

在相应的 app.component.html 中,title将包含如下:

<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 个答案:

答案 0 :(得分:1)

如果需要使用整个应用程序结构中提供的全局变量,则可以使用共享服务,您必须将其置于共享模块中。

您可以在此处阅读有关共享模块的信息:

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

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

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

事实上,我认为在任何应用程序中都有这样的东西不是一个好主意。