2016-06-01 17 views
0

モデルのリストを表示するトップメニュー(Component)と、色のリストを表示するサイドメニュー(Component)があります。私のページの中央には、色とモデルコントロールのユーザー選択に基づいて物のリストを表示するテーブル(Component)があります。 コントロールのいずれも他のコントロールの子ではありません。テーブルコンポーネントは、ルータコンセントコンテナにレンダリングされます。角型2コンポーネント間通信

テーブルコンポーネントで2つのメニューコンポーネントのプロパティの変更をリッスンする方法を教えてください。ここで説明するように

私はすでにセッションサービスを試してみました:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-servicehttps://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

テーブルコンポーネントは、メニューコンポーネントの子ではありませんので、それは動作しません。

答えて

3

私はそれのためのシンプルなサービスになるだろう:

constructor(private _filterService:FilterService){} 
// method invoked by user's action 
onSelect(value) { 
    this._filterService.setModel(value); // or setColor() 
} 

とTableComponentは、イベントのためにサブスクライブします:次にTopMenuComponentとSideMenuComponentは、サービスのセッターを呼び出します

@Injectable() 
export class FilterService { 
    public modelChange$:EventEmitter; 
    public colorChange$:EventEmitter; 

    constructor(){ 
     this.modelChange$ = new EventEmitter(); 
     this.colorChange$ = new EventEmitter(); 
    } 

    public setModel(model):void{ 
     this.modelChange$.emit(model); 
    } 

    public setColor(color):void{ 
     this.colorChange$.emit(color); 
    } 
} 

constructor(private _filterService:FilterService){ 
    this._filterService.modelChange$.subscribe(model => console.log("new model: " + model)); 
    this._filterService.colorChange$.subscribe(color => console.log("new color: " + color)); 
} 

私は内部のアーティストを使って、それがどう動くかを示しました: at least i tried to

希望しました。

+0

優秀、ありがとうございました! – Sam

関連する問題