2017-02-09 32 views
1

想象一下,我們有3個組件,其中一個組件有一些我想在其他組件中使用的功能。所有這些組件都在同一級別(兄弟姐妹)。Angular 2 - 如何使用另一個組件的功能?

file1.ts 
export class ComponentWithFunction() { 
    function getData() { 
     console.log('data has been fetched'); 
    } 
} 

file2.ts 
export class ComponentA() { 
    // here I want to have possibility to use getData 
} 

file3.ts 
export class ComponentB() { 
    // here I want to have possibility to use getData 
} 

我該怎麼做才能從其他組件獲取getData函數?我知道我可以創建SharedService並將其注入到指定的組件中,但有沒有其他方式使用靜態函數或類似的東西?

謝謝

回答

6

爲什麼組件? Angular 2表示,您必須使用服務來檢索數據,並將數據訪問重構爲單獨的服務,使組件精益求精,並專注於支持視圖。它還使得使用模擬服務對組件進行單元測試變得更加容易。

你可以把它放進serviceservice每個Component在要使用該功能inject

加入該服務爲app module's providers,注入的構造類似

file1.ts 

@Injectable() 
export class ComponentWithFunction() { 
    function getData() { 
     console.log('data has been fetched'); 
    } 
} 

file2.ts 
export class ComponentA() { 
    constructor(private service: ComponentWithFunction) 
} 

file3.ts 
export class ComponentB() { 
    constructor(private service: ComponentWithFunction) 
} 

更多看到Service in Angular 2

+0

作爲一個經驗法則,總是用服務來獲取數據 參見:https://angular.io/docs/ts/latest/tutorial/toh-pt4.html 「我們創建了一個可重用的服務來管理我們的英雄數據通話「 – hkievet

+0

@ user3844198如果這可以幫助您,您可以標記爲正確並幫助他人輕鬆找到它 –

0

所以,也許是不同的例子。

假設我的頁面上有組件負責模態元素。 這樣的組件的上下文有一個邏輯,如打開,關閉,刷新等方法。

據我所知,要使用不同組件的open()或close()方法,我必須將Modal創建爲服務並將其注入到我想要使用它的所有位置?沒有選擇訂閱Modal的活動/方法?

+0

請參閱此處。你需要添加你的模態組件到另一個是嗎?所以你可以給你的模態組件一個模板變量,比如',並用'@ViewChild('myModal')modal'在你的組件中獲取該元素。並且該模式組件上的所有公共函數都可以通過'modal'在組件中訪問 –

相關問題