RxJS fromEvent operator with output EventEmitter in Angular

偶尔善良 提交于 2019-12-12 13:19:35

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!