2017-02-23 60 views
0

我有發出的號碼的子組件:如何從子組件與可觀察到的在父使用EventEmitter(角2)

this.number.emit(3); 

在父組件我聽聽吧:

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

在父類中,如何將父組件中的EventEmitter與父組件中的observable結合起來?

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

回答

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) 
    } 
} 
1

下面嘗試,

@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

希望這有助於!