2017-02-23 91 views
2

在Angular2中,假设我有component1(用作左侧面板导航器)和component2。这两个组件彼此不相关(同级,父级和子级...) 。 如何从component2调用component1中的函数? 我不能在这里使用事件绑定。在另一个组件中调用一个组件的函数

+0

你可能会使用一个[服务](https://angular.io/docs/ts/latest/tutorial/toh-pt4.html)来管理该连接。 – ryannjohnson

+0

使用流量模式 - 服务是事件的调度程序,组件是订户。组件并不真正了解对方。这可能是有用的:http://stackoverflow.com/questions/42219858/how-can-i-maintain-the-state-of-dialog-box-with-progress-all-over-my-angular-2-a/42221273#42221273 – pixelbits

+0

@ryannjohnson在component1中,我有内插{{total}},需要立即更新并显示在左侧面板中。如果我只是致电服务,我该如何更新这个变量? –

回答

2

共享服务是非相关组件之间通用的通信方式。 您的组件需要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

+0

这是否仍然工作10/24/2017?尝试完全按照指定,但从comp2调用时,comp1的名称出现未定义。 – overboard182

0

可以使用角行为主题与非相关组件进行通信。

服务文件

import { Injectable } from '@angular/core'; 
import { BehaviorSubject } from 'rxjs/BehaviorSubject'; 


@Injectable() 
export class commonService { 
    private data = new BehaviorSubject(''); 
    currentData = this.data.asObservable() 

    constructor() { } 

    updateMessage(item: any) { 
     this.data.next(item); 
    } 

} 

第一组分

constructor(private _data: commonService) { } 
shareData() { 
     this._data.updateMessage('pass this data'); 
} 

第二部分

constructor(private _data: commonService) { } 
ngOnInit() { 
    this._data.currentData.subscribe(currentData => this.invokeMyMethode()) 
} 

使用ABOV您可以使用非相关组件轻松调用方法/共享数据。

More info here

相关问题