在我們的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