问题描述
说有一个ChildComponent
,它发出一个称为someEvent
的事件.显然,我可以在ParentComponent
中捕获声明为<child-component (someEvent)="onSomeEvent($event)"></child-component>
的事件,并使用ParentComponent
中的方法onSomeEvent
处理该事件.但是我正在尝试的是我想用RxJS中的fromEvent
运算符处理事件.在使用@ViewChild
获取ChildComponent
的ElementRef
之后,我尝试了fromEvent(this.childComponent.nativeElement, 'someEvent')
.我发现如果输出EventEmitter的事件名称与诸如click
之类的本机事件之一相同,则上述方法有效,但否则不会响应/不起作用.有什么方法可以使其与fromEvent
一起使用?
Say there's ChildComponent
which emits out an event called someEvent
. Obviously, I can catch the event in ParentComponent
declaring like, <child-component (someEvent)="onSomeEvent($event)"></child-component>
and handle it with the method onSomeEvent
in ParentComponent
. But what I'm trying is that I want to handle the event with fromEvent
operator in RxJS. I've tried fromEvent(this.childComponent.nativeElement, 'someEvent')
after getting the ElementRef
of the ChildComponent
with @ViewChild
. I discovered that the above approach works if the output EventEmitter's event name is the same as one of the native events such as click
but it doesn't respond/work otherwise. Is there any ways to make it work with fromEvent
?
推荐答案
如果要将事件转换为可观察的事件,可以使用Subject
,如下所示:
If you want to convert the event into an observable, you could use a Subject
, like this:
@Component({
selector: 'parent-component',
template: `
<child-component (someEvent)="subject.next($event)">
</child-component>
`
})
export class ParentComponent {
public subject = new Subject<any>();
constructor() {
this.subject.pipe(
tap(event => console.log(event)) // or whatever
).subscribe();
}
}
这样做将为您提供一个可观察的来源-主题-发出事件发射器发出的任何值.由此,您可以使用RxJS运算符编写任何内容.
Doing so will provide you with an observable source - the subject - that emits whatever value the event emitter emits. From that you can compose whatever you want using RxJS operators.
这篇关于RxJS fromEvent运算符,在Angular中具有输出EventEmitter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!