How to broadcast events from app.component to router-outlet in angular2

前端 未结 1 958
我寻月下人不归
我寻月下人不归 2021-01-03 04:51

I have created a service that has a stream$ that will emit an event, I hope after the app.component fires the stream$ emit, the child component in the

相关标签:
1条回答
  • 2021-01-03 05:53

    The most simple way is to create event bus service:

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

    Use dependency injection:

    bootstrap(App, [EventBusService]);
    

    Component constructor:

    constructor(bus:EventBusService){
       bus.dispatch(new Event());
       bus.listen('load').subscribe((e)=>{console.log('loaded');})
    }
    
    0 讨论(0)
提交回复
热议问题