2017-02-23 89 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

相關問題