问题
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?
回答1:
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();
}
}
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.
来源:https://stackoverflow.com/questions/49228081/rxjs-fromevent-operator-with-output-eventemitter-in-angular