本文介绍了RxJS fromEvent运算符,在Angular中具有输出EventEmitter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说有一个ChildComponent,它发出一个称为someEvent的事件.显然,我可以在ParentComponent中捕获声明为<child-component (someEvent)="onSomeEvent($event)"></child-component>的事件,并使用ParentComponent中的方法onSomeEvent处理该事件.但是我正在尝试的是我想用RxJS中的fromEvent运算符处理事件.在使用@ViewChild获取ChildComponentElementRef之后,我尝试了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 07:22