从另一个组件调用组件中的函数 [英] call a function in a component from another component
本文介绍了从另一个组件调用组件中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Angular2中,假设我有component1(使用它作为左面板导航器)和component2。这两个组件彼此无关(兄弟,父子和子...)。
如何从component2调用component1中的函数?
我不能在这里使用事件绑定。
In Angular2 , assume I have component1(use it as left panel navigator) and component2 .these two components are not related to each other (sibling, parent and child, ...). how can I call a function in component1 from component2? I cant use event binding here.
推荐答案
共享服务是非相关组件之间通用的常用方式。
您的组件需要使用单个实例的服务,所以请确保它在根级别提供。
Shared service is a common way of communication between non-related components. Your components need to use a single instance of the service, so make sure it's provided at the root level.
共享服务:
@Injectable()
export class SharedService {
componentOneFn: Function;
constructor() { }
}
组件一:
export class ComponentOne {
name: string = 'Component one';
constructor(private sharedService: SharedService) {
this.sharedService.componentOneFn = this.sayHello;
}
sayHello(callerName: string): void {
console.log(`Hello from ${this.name}. ${callerName} just called me!`);
}
}
组件二:
export class ComponentTwo {
name: string = 'Component two';
constructor(private sharedService: SharedService) {
if(this.sharedService.componentOneFn) {
this.sharedService.componentOneFn(this.name);
// => Hello from Component one. Component two just called me!
}
}
}
这篇关于从另一个组件调用组件中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文