在我们的NG启动样板app.component.ts我有这样的代码:使用Angular 2 Services来传递全局变量?
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>
谢谢。为什么这是一个坏主意? – abrahamlinkedin
在上面的例子中,你可以看到该变量是公开的。这不是一个好习惯,因为数据不是不可变的,你可以改变它的值,例如错误:) –
@abrahamlinkedin,如果你没有在这个服务的构造函数中注入任何东西,'@Injectable()'装饰器不是必须的。 – rook