Angular 如何从子组件使用EventEmitter,并在父组件中可观察(角度2)
我有一个子组件,它发出一个数字:Angular 如何从子组件使用EventEmitter,并在父组件中可观察(角度2),angular,rxjs,Angular,Rxjs,我有一个子组件,它发出一个数字: this.number.emit(3); 在父组件中,我听它: <parent> <child (number)="$event"></child> </parent> 必须在父零部件中手动创建一个。您需要向该主题提供来自发出事件的数据,并在combinelateest方法中使用它。实现将如下所示: import Subject from 'rxjs/Subject' @Component({ //
this.number.emit(3);
在父组件中,我听它:
<parent>
<child (number)="$event"></child>
</parent>
必须在父零部件中手动创建一个。您需要向该主题提供来自发出事件的数据,并在
combinelateest
方法中使用它。实现将如下所示:
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)
}
}
从“rxjs/Subject”导入主题
@组成部分({
//将事件从子组件转发到numberChanges主题。
模板:``
})
班级家长{
numberChanges=新主题()
//假设您在onInit方法中创建流。
恩戈尼尼特(){
const stream=this.apiService.getSomeHTTPRequest()
//合并数字更改流。
.CombineRelatest(此.numberChanges)
}
}
试试下面的方法
@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);
});
}
}
@组件({
选择器:“我的应用程序”,
模板:`Hello{{name}}
`
})
导出类AppComponent{
名称='角度';
儿童编号:主题
希望这能有所帮助!!因为每个事件发射器
实际上都是一个可观察的(主题
),所以你可以订阅它(或者将它与其他可观察的对象组合)
您应该获得子组件:
@ViewChild(ChildComponent,{static:true})child:ChildComponent;
然后,您可以订阅(或组合)子项的EventEmitter
s:
child.number.subscribe();
使用此技术,您不需要侦听模板中的事件:
@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);
});
}
}