2017-02-09 56 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'在组件中访问 –

相关问题