如何在 Angular 2 中将事件从深层嵌套的子级传递给父级? [英] How pass a event from deep nested child to parent in Angular 2?
问题描述
我有一个嵌套的子组件,它有一个输出事件,我想从父组件监听这个事件,但我不知道怎么做,我有 4 个级别:
I have a nested child component that have a output Event, I want listen this event from parent component but I dont know how, I have 4 levels:
我尝试将事件从孩子 3 传递给孩子 2,将孩子 2 传递给孩子和家长,但我认为这不是最好的方式.
I tried to pass the event from child 3 to child 2 and child 2 to child and to Parent, but I think that this is not the best way.
-Parent (From this I want listen the event)
--Child
----Child 2
------Child 3 (This have the Event)
推荐答案
Source Dan Wahlin (ng-conf: Mastering the Subject: Communication Options in RxJS ), 不建议使用 OutPut有一个更深层次的组件必须与更高级别的组件通信,假设您有 5 或 6 个级别!!,您必须使用 Subject 代替:您可以通过可观察服务创建事件总线
Source Dan Wahlin (ng-conf: Mastering the Subject: Communication Options in RxJS ), it's not recommanded to use OutPut when you have a component in a deeper level that has to communicate with a higher lever component , imagine you have 5 or 6 leves!!, you have to use Subject instead: you can create and Event bus through an observable service
这里的事件是事件的枚举,如果你愿意的话
Events here is an enum of events if you want
export enum Events{
'payment done',
// other events here
}
@Injectable()
export class EventService {
private subject$ = new Subject()
emit(event: EmitEvent) {
this.subject$.next(event);
}
on(event: Events, action: any): Subscription {
return this.subject$.pipe(
filter((e: EmitEvent) => e.name == event),
map((e: EmitEvent) => e.value)).subscribe(action);
}
}
现在假设您想从 Child3 发出一个事件,例如在付款完成后 => 通知父组件
so now imagine that you want to emit an event from Child3 , let's say for example after a payment is done => notify parent component
export class Child3Component implements OnInit {
constructor(public eventservice : EventService ) {}
pay(paymentAmount: any) {
this.eventservice.emit(
new EmitEvent('payment done',paymentAmount));
}
}
现在在你的父组件中你可以调用这样的方法,你会得到事件
now in your parent component you can call on method like this and you will get the event
export class ParentComponent implements OnInit {
constructor(public eventservice : EventService ) {}
ngOnInit() {
this.eventservice.on('payment done', (paymentAmount => console.log(paymentAmount));
}
}
这篇关于如何在 Angular 2 中将事件从深层嵌套的子级传递给父级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!