如何使用子组件中的 EventEmitter 和父组件中的可观察对象(角度 2)

Nik*_*Nik 3 rxjs angular

我有一个发出数字的子组件:

this.number.emit(3);
Run Code Online (Sandbox Code Playgroud)

在父组件中我听它:

<parent>
  <child (number)="$event"></child>
</parent>
Run Code Online (Sandbox Code Playgroud)

在父类中,如何将子组件中的 EventEmitter 与父组件中的可观察对象结合起来?

this.apiService.getSomeHTTPRequest()
    .combineLatest(--- ??? combine with child event emitter ??? ---)
Run Code Online (Sandbox Code Playgroud)

Mat*_*ocz 5

您必须在父组件中手动创建主题。您需要向该主题提供来自发出事件的数据并在方法中使用它combineLatest。实现将如下所示:

import Subject from 'rxjs/Subject'
@Component({
    // Forward events from the child component to the numberChanges subject.
    template: `<child (number)="numberChanges.next($event)"></child>`
})
class Parent {
    numberChanges = new Subject<number>()
    // Assuming you create the stream in onInit method.
    ngOnInit() {
         const stream = this.apiService.getSomeHTTPRequest()
             // Combine the numberChanges stream.
             .combineLatest(this.numberChanges)
    }
}
Run Code Online (Sandbox Code Playgroud)