2016-04-21 55 views
2

我已經創建了一個服務,它有一個流$,它將發出一個事件,我希望在app.component觸發流之後發出$ emit,子組件<router-outlet></router-outlet>將能夠訂閱它,但現在我遇到的問題是,即使它在構造函數中訂閱它,訂閱回調也不會被觸發。如何將事件從app.component廣播到angular2中的router-outlet

我不知道這是否與通過流服務發佈事件不同?

最佳做法是什麼?

+0

這是我實現這樣的服務的它允許在訂閱時獲得第n個最後的值。 https://stackoverflow.com/questions/46027693/angular2-4-broadcast-service-using-rxjs – Codewarrior

回答

6

最簡單的方法是創建事件總線服務:

export class EventBusService 
{ 
    bus:Subject<Event> = new Subject<Event>(); 

    dispatch(data:Event){ 
     this.bus.next(data); 
    } 

    //its up to you how to implement it: 
    listen(type:string):Observable<Event> { 
     return this.bus.filter(event=>event.type === type); 
    } 
} 

使用依賴注入:

bootstrap(App, [EventBusService]); 

組件構造:

constructor(bus:EventBusService){ 
    bus.dispatch(new Event()); 
    bus.listen('load').subscribe((e)=>{console.log('loaded');}) 
}