如何在angular2中将事件从app.component广播到router-outlet [英] How to broadcast events from app.component to router-outlet in angular2
本文介绍了如何在angular2中将事件从app.component广播到router-outlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个服务,它有一个将发出事件的流 $,我希望在 app.component 触发流 $ 发出后,<router-outlet></router 中的子组件-outlet>
将能够订阅它,但现在我遇到的问题是即使它在构造函数中订阅它,订阅回调也永远不会被触发.
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?
最佳做法是什么?
推荐答案
最简单的方法就是创建事件总线服务:
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);
}
}
使用依赖注入:
bootstrap(App, [EventBusService]);
组件构造函数:
constructor(bus:EventBusService){
bus.dispatch(new Event());
bus.listen('load').subscribe((e)=>{console.log('loaded');})
}
这篇关于如何在angular2中将事件从app.component广播到router-outlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文