gpt4 book ai didi

angular - 如何在 Angular 2 中将事件从深层嵌套的子级传递给父级?

转载 作者:行者123 更新时间:2023-12-04 15:38:49 25 4
gpt4 key购买 nike

我有一个嵌套的子组件,它有一个输出事件,我想从父组件监听这个事件,但我不知道如何,我有 4 个级别:

我试图将事件从 child 3 传递给 child 2,将 child 2 传递给 child 和 parent ,但我认为这不是最好的方法。

-Parent (From this I want listen the event)
--Child
----Child 2
------Child 3 (This have the Event)

最佳答案

来源 丹华林 (ng-conf: Mastering the Subject: Communication Options in RxJS ),当你有一个更深层次的组件必须与更高级别的组件通信时,不建议使用 OutPut ,想象你有 5 或 6 个级别!!,您必须使用 主题 反而:
您可以通过可观察服务创建和事件总线

如果您愿意,这里的事件是事件的枚举

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 , 例如在付款完成后 => 通知父组件
export class Child3Component implements OnInit {

constructor(public eventservice : EventService ) {}
pay(paymentAmount: any) {
this.eventservice.emit(
new EmitEvent('payment done',paymentAmount));
}
}

现在在您的父组件中,您可以像这样调用方法,您将获得事件
 export class ParentComponent implements OnInit {
constructor(public eventservice : EventService ) {}
ngOnInit() {
this.eventservice.on('payment done', (paymentAmount => console.log(paymentAmount));
}
}

关于angular - 如何在 Angular 2 中将事件从深层嵌套的子级传递给父级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56290722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com