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

jua*_*rio 5 events components parent-child angular

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

我试图将事件从孩子3传递给孩子2,将孩子2传递给孩子并传递给父母,但是我认为这不是最好的方法。

-Parent (From this I want listen the event)
--Child
----Child 2
------Child 3 (This have the Event)
Run Code Online (Sandbox Code Playgroud)

Fat*_*med 10

来源Dan Wahlin(ng-conf:掌握主题:RxJS 中的通信选项),当您有一个更深层次的组件必须与更高级别的组件进行通信时,不建议使用 OutPut,假设您有 5 或 6 个级别!!,你必须使用Subject:你可以通过一个可观察的服务创建和事件总线

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

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

}
Run Code Online (Sandbox Code Playgroud)

所以现在想象你想从Child3发出一个事件,例如在付款完成后=> 通知父组件

export class Child3Component implements OnInit {

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

现在在您的父组件中,您可以像这样调用方法,您将获得事件

 export class ParentComponent implements OnInit {
   constructor(public eventservice : EventService ) {}
   ngOnInit() {
    this.eventservice.on('payment done', (paymentAmount => console.log(paymentAmount));
   }
 }
Run Code Online (Sandbox Code Playgroud)


Dan*_*l B 6

尽管您可以使用@Output事件发射器来执行此操作,但我建议您创建一个共享服务来代替处理通信,因为有很多嵌套级别。

您可以执行以下操作,并将服务注入到您的两个组件中。一个将发出消息(您的嵌套子组件),另一个将侦听消息(您的顶级组件)。

定义您的服务

@Injectable({
    providedIn: 'root'
})
export class CommunicationService {
    @Output() message$: EventEmitter<boolean> = new EventEmitter();

    sendMessage(message: String) {
        this.change.emit(message)
    }
}
Run Code Online (Sandbox Code Playgroud)

将它注入到你的组件中

constructor(private communicationService: CommunicationService) { }
Run Code Online (Sandbox Code Playgroud)

在您将发送消息的组件中

sendMessage() {
    this.communicationService.sendMessage('This is a message from deep below!');
}
Run Code Online (Sandbox Code Playgroud)

在您的侦听器组件中,订阅事件发射器

ngOnInit() {
    this.communicationService.message$.subscribe(message => {
      console.log(message);
    });
}
Run Code Online (Sandbox Code Playgroud)