想象一下,我们有3个组件,其中一个组件具有一些我想在其他组件中使用的功能。所有这些组件都在同一级别(兄弟姐妹)。
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并将其注入指定的组件,但还有其他方法,比如使用静态函数或类似的东西吗?
谢谢
答案 0 :(得分:6)
为什么是组件? Angular 2说,您必须使用服务来检索数据并重构数据访问单独的服务,使组件保持精简并专注于支持视图。它还可以更容易地使用模拟服务对组件进行单元测试。
您可以将其放入要使用该功能的每个plz-center
中service
和inject
的{{1}}。
将该服务添加到service
并注入构造函数,如
Component
有关详情,请参阅Service in Angular 2。
答案 1 :(得分:0)
所以,也许是不同的例子。
假设我在页面上有Component负责模态元素。 这种组件的上下文有一个逻辑,方法如open,close,refresh等。
据我所知,要使用不同组件的open()或close()方法,我必须创建Modal作为服务并将其注入我想要使用它的所有地方吗?没有选择从Modal订阅事件/方法?