如何在Angular 2中将事件从深层嵌套子级传递给父级? [英] How pass a event from deep nested child to parent in Angular 2?

查看:186
本文介绍了如何在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)

推荐答案

来源 Dan Wahlin (ng-conf:掌握主题: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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆