【问题标题】:How to use EventEmitter from child component with observable in parent (angular 2)如何使用子组件中的 EventEmitter 与父组件中的 observable(角度 2)
【发布时间】:2017-07-14 09:56:00
【问题描述】:

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

this.number.emit(3);

在父组件中我监听它:

<parent>
  <child (number)="$event"></child>
</parent>

在父类中,如何将子组件中的 EventEmitter 与父组件中的 observable 结合起来?

this.apiService.getSomeHTTPRequest()
    .combineLatest(--- ??? combine with child event emitter ??? ---)

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    您必须在父组件中手动创建Subject。您需要向该主题提供来自已发出事件的数据,并在 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)
        }
    }
    

    【讨论】:

      【解决方案2】:

      试试下面,

      @Component({
        selector: 'my-app',
        template: `<h1>Hello {{name}}</h1>
        <my-child (number)="childNumber.next($event)" ></my-child>
        `
      })
      export class AppComponent {
        name = 'Angular';
        childNumber: Subject<any>= new Subject<any>();
      
        someAPI = Observable.interval(2000);
        combined = Observable.combineLatest(this.childNumber,this.someAPI);
      
        constructor(){
          this.combined.subscribe(latestVals => console.log(latestVals));
        }
      }
      
      
      @Component({
        selector: 'my-child',
        template: `<h3>Child Component</h3>`
      })
      export class ChildComponent { 
        @Output() number: EventEmitter<any> = new EventEmitter<any>();
      
        constructor(){
          Observable.interval(1000).subscribe(num => {
            this.number.emit(num);
          });
        }
      }
      

      检查这个Plunker!!

      希望这会有所帮助!

      【讨论】:

        【解决方案3】:

        由于每个EventEmitter 实际上都是Observable(准确地说是Subject),因此您可以订阅它(或将其与其他可观察对象结合使用)。

        你应该得到子组件:

        @ViewChild(ChildComponent, { static: true }) child: ChildComponent;
        

        然后,您可以订阅(或合并)孩子的EventEmitters:

        child.number.subscribe();
        

        使用这种技术,您不需要在模板中监听事件:

        <parent>
          <child></child>
        </parent>
        

        StackBlitz

        【讨论】:

          猜你喜欢
          • 2020-10-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-24
          • 1970-01-01
          • 2017-05-18
          • 2020-05-22
          • 1970-01-01
          相关资源
          最近更新 更多