2016-09-13 58 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