2017-07-04 9 views
5

達成しようとしています私は、グローバルangular2でカスタムイベントを放出し、複数のコンポーネントが私のイベント・ソース・コンポーネントではそうではないだけで親子パターン発光イベントグローバル

それに耳を傾けるがしたいですが、私は持っています

export class EventSourceComponent{ 

    @Output() testev = new EventEmitter(); 

    onbtnclick(){ 
    this.testev.emit("i have emitted an event") 
    } 
} 

今私はどのように私は上記目的を達成ん

export class CmpTwoComponent{ 

    //here get the emitted event with data 
    } 

このイベントを取得するために他のコンポーネントをご希望ですか?

答えて

3

これには共有サービスを使用できます。

export class EventSourceComponent{ 
    constructor(private sharedService : SharedService){} 


     onbtnclick(){ 
     this.sharedService.testev.next("i have emitted an event") 
     } 
} 

export class CmpTwoComponent{ 

//here get the emitted event with data 

    constructor(sharedService : SharedService){ 

     sharedService.testev.subscribe((event)=>{console.log(event)}) 
    } 

} 

、あなたはまだあなたがあまりにもそれを追加することができ、その親コン​​ポーネントが正常に購読することができ可能性Outputを必要とするならば、sharedServiceは、

明らか
@Injectable() 
export class SharedService{ 

    public testev = new Subject() 

} 

次のようになります。

export class EventSourceComponent{ 

    @Output() testev = new EventEmitter(); 
    constructor(private sharedService : SharedService){} 


     onbtnclick(){ 
     this.testev.emit("i have emitted an event") 
     this.sharedService.testev.next("i have emitted an event") 
     } 
} 
+0

サービス内では 'EventEmitter'を使用しないでください。 https://stackoverflow.com/questions/36076700/what-is-the-proper-use-of-an-eventemitter代わりに 'Observable' /' Subject'を使用してください。 – echonax

+0

素晴らしいmiladありがとう –

1

あなたが求めているものを達成するための角度のパターンはありません。

私が考えることのできる最良の選択肢は、カスタムサービスを作成することです。 AppComponentに注入するサービスを作成します(したがって、サービスの単一インスタンスを持つ)。サービスでは、必要なロジックを自由に設定することができます。

+0

角度2の世界的な出来事に関しては、これを見てみるとよいでしょう:https://modewagon.wordpress.com/2017/09/12/angular2-4-global-events/ –

関連する問題