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

不羁的心 提交于 2019-12-03 20:21:32

问题


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 <router-outlet></router-outlet> will be able to subscribe it, but now the problem I have is even if it subscribes it in the constructor, the subscription call back never gets fired.

I wonder if this is different from when emitting events through a stream service?

What is the best practice?


回答1:


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


来源:https://stackoverflow.com/questions/36781993/how-to-broadcast-events-from-app-component-to-router-outlet-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!