想象一下,我们有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如果这可以帮助您,您可以标记为正确并帮助他人轻松找到它 –