【问题标题】:Downwards and Upwards events向下和向上事件
【发布时间】:2016-03-27 14:53:28
【问题描述】:

我正在尝试 angular 2,我认为它很棒! 但我不知道如何发出/订阅事件。

例如: 我有两个小组件:componentA 和 componentB。 ComponentA 包含一个水果列表。 ComponentB 包含水果的详细信息。当用户从列表(componentA)中选择一个水果时,我希望 ComponentB 执行一个函数(例如 console.log(event))。

为了实现这种行为,我想使用事件。 ComponentA 不是componentB 的父级,它们是兄弟。但我希望事件向下和向上传播。 任何知道活动名称的人都必须能够订阅此活动。

有可能吗? 我想使用 angular2 类,而不是外部库。

我当前的代码:

export class ComponentA
{
    @Output() emitter: EventEmitter<string> = new EventEmitter();

    private onFruitSelected():void
    {
        this.emitter.emit ("Hello!");
    }
}


export class ComponentA
{
    constructor ():void
    {
        // subscribe doJob() to the event
    }

    private doJob ():void { console.log('event catched'); }
}

谢谢!

编辑

我是这样更新代码的:

事件处理服务:

export class EventEmitterService 
{
    @Output() eventOne: EventEmitter<string> = new EventEmitter();
    @Output() eventTwo: EventEmitter<number> = new EventEmitter();
}

componentA(事件发送者):

export class ComponentA
{
    public constructor(private eventHandler:EventEmitterService) {}

    private onFruitSelected():void
    {
        this.emitter.emit ("Hello!");
        this.eventHandler.eventOne.emit ("Hello event one");
        this.eventHandler.eventTwo.emit (12);
    }
}

componentB(事件接收器):

export class ComponentA
{
    constructor ():void
    {
        eventHandler.eventOne.subscribe ((evt:string) => { 
            console.log ('Event one ' + evt); 
        });

        eventHandler.eventTwo.subscribe ((evt:number) => { 
            console.log ('Event two ' + evt); 
        });
    }
}

这是一个好的解决方案吗?

【问题讨论】:

    标签: angular


    【解决方案1】:

    Angular2 没有为此提供功能。 您可以使用自定义事件总线服务。 另见

    【讨论】:

    • 感谢您的回答!我刚刚更新了我的问题,您对解决方案有何看法?再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多