我找到了两种方法来实现这一点:
1.将主要组件注入子组件
您可以向主组件添加事件,将主组件注入子组件并订阅事件。请参阅说明这一点的plunk。但是,现在您的孩子依赖于您的主要组件。这可能不太好。
主要组件
executeAction: EventEmitter<any> = new EventEmitter();
constructor() { }
performAction() {
this.executeAction.emit();
}
孩子
constructor(private appComponent: AppComponent) {
this.executeAction = this.executeAction.bind(this);
eventSubscriber(appComponent.executeAction, this.executeAction);
}
ngOnDestroy(): void {
eventSubscriber(this.appComponent.executeAction, this.executeAction, true);
}
executeAction() {
alert('1');
}
2。实施服务
这里和Parent and children communicate via a service 中描述的最佳解决方案是创建一个服务,该服务将成为主要组件和子组件之间的附加层。这样,您将独立于主要组件实现。请参阅说明此方法的 plunk。
服务
subscription = new Subject();
executeAction() {
this.subscription.next();
}
主要组件
constructor(private appService: AppService) { }
performAction() {
this.appService.executeAction();
}
孩子
constructor(private appService: AppService) {
this.executeAction = this.executeAction.bind(this);
eventSubscriber(appService.subscription, this.executeAction);
}
ngOnDestroy(): void {
eventSubscriber(this.appService.subscription, this.executeAction, true);
}
executeAction() {
alert('1');
}