【问题标题】:How can I emit an event passing the emitter inside a function in Angular 2如何在 Angular 2 中的函数内发出传递发射器的事件
【发布时间】:2016-11-28 15:49:48
【问题描述】:

组件父(模板):

<CHILD></CHILD>
<overlayer *ngIf="showPopup" (evTogglePopup)="onShowPopup($event)"></overlayer>

组件子(@Component):

@Output() evTogglePopup = new EventEmitter();
...
this.inputUt.ajaxCheckExistingEmail(email, this.evTogglePopup);

MyInputUtility 的一个功能(导入并用于 CHILD 的提供程序 @Injectable):

ajaxCheckExistingEmail(email, evEmitter:EventEmitter<any>){
        if (email.valid){
            return this.http.post(
                GLOBAL_CONST.apiPath + "/user/user/api-check-user-email",
                'email=' + email.value,
                {headers: this.headers}
            ).map(response => response.json())
            .subscribe(val => {
                console.log(val);
                if( val.emailExists ){
                    evEmitter.emit(true);
                }
            });
        }
}

这个“解决方案”不起作用,我想知道是不是因为 evEmitter 是通过副本传递给 ajaxCheckExistingEmail 函数的。

我自己做的
问题是“覆盖层”是一种不同的选择器形式,与 CHILD(选择器)指向的选择器形式不同,我认为它也可以工作。

我在下面进行了这样的更改,现在它可以工作了:

<CHILD (evTogglePopup)="onShowPopup($event)"></CHILD>
    <overlayer *ngIf="showPopup"></overlayer>

【问题讨论】:

  • evTogglePopup 是一个对象,对象不是通过复制传递,而是通过引用传递。什么不起作用?怎么不行?
  • 只是在包含事件侦听器的组件中的“evEmitter.emit(true)”之后/使用“evEmitter.emit(true)”之后没有发出事件
  • 我更新了问题
  • 孩子是&lt;overlayer&gt;?从哪里调用this.inputUt.ajaxCheckExistingEmail(email, this.evTogglePopup);
  • 又更新了,应该清楚了……

标签: typescript angular eventemitter emit


【解决方案1】:

来自@Output() 的事件不会冒泡。您可以将其从一个父级传递到下一个父级,也可以使用共享服务在不处于直接父子关系的元素之间共享数据。

详情请见https://angular.io/docs/ts/latest/cookbook/component-communication.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 2021-05-22
    相关资源
    最近更新 更多