Dow*_*ski 4 rxjs angular2-routing angular
我已经创建了一个服务,它有一个将发出一个事件的流$,我希望在app.component激发流$ emit后,子组件<router-outlet></router-outlet>
将能够订阅它,但现在我遇到的问题是即使它在构造函数中订阅它,订阅回调永远不会被触发.
我想知道这是否与通过流服务发送事件时不同?
什么是最佳做法?
最简单的方法是创建事件总线服务:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
使用依赖注入:
bootstrap(App, [EventBusService]);
Run Code Online (Sandbox Code Playgroud)
组件构造函数:
constructor(bus:EventBusService){
bus.dispatch(new Event());
bus.listen('load').subscribe((e)=>{console.log('loaded');})
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1489 次 |
最近记录: |