想象一下,我們有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並將其注入到指定的組件中,但有沒有其他方式使用靜態函數或類似的東西?
謝謝
作爲一個經驗法則,總是用服務來獲取數據 參見:https://angular.io/docs/ts/latest/tutorial/toh-pt4.html 「我們創建了一個可重用的服務來管理我們的英雄數據通話「 – hkievet
@ user3844198如果這可以幫助您,您可以標記爲正確並幫助他人輕鬆找到它 –