如何将事件从app.component广播到angular2中的路由器出口 [英] How to broadcast events from app.component to router-outlet in angular2

查看:74
本文介绍了如何将事件从app.component广播到angular2中的路由器出口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个具有流$的服务,该流将发出事件,我希望在app.component触发stream $发出后,<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');})
}

这篇关于如何将事件从app.component广播到angular2中的路由器出口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆