在Angular2中,假设我有component1(使用它作为左面板导航器)和component2.这两个组件彼此不相关(兄弟,父和子,……).
如何从component2调用component1中的函数?
我不能在这里使用事件绑定.
如何从component2调用component1中的函数?
我不能在这里使用事件绑定.
共享服务是非相关组件之间通信的常用方式.
您的组件需要 use a single instance of the service,因此请确保它在根级别提供.
您的组件需要 use a single instance of the service,因此请确保它在根级别提供.
共享服务:
- @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!
- }
- }
- }
这篇文章也许有帮助:Angular 2 Interaction between components using a service