2017-02-23 15 views
2

Angular2では、component1(左のパネルナビゲータとして使用)とcomponent2(これらの2つのコンポーネントは互いに兄弟、親、子など) 。 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() { } 
} 

コンポーネント1:

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!`); 
    } 
} 

コンポーネント2:

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

これはまだ2011年10月24日に動作しますか?指定したとおりに正確に試しましたが、comp2から呼び出されたときにcomp1の名前は未定義と表示されます。 – overboard182

0

関連のないコンポーネントと通信するために、角度BehaviorSubjectを使用できます。 abovを使用して

サービスファイル

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()) 
} 

メソッドを呼び出して、関連していないコンポーネントと簡単にデータを共有することができます。

More info here

関連する問題