首页 > 解决方案 > 来自多个孩子的输出和发射器

问题描述

我的 app.component 中有一个侧边栏。我希望能够从多个子组件更新它。这里有一个关于如何将数据从子组件发送到父组件的示例:

https://dzone.com/articles/understanding-output-and-eventemitter-in-angular

但是,该示例将父组件绑定到特定的子组件:

import { Component, OnInit } from '@angular/core';
@Component({
    selector: 'app-root',
    template: `<app-child></app-child>`
})
export class AppComponent implements OnInit {
    ngOnInit() {
    }
}

如您所见,模板绑定到特定于 app-child 的模板。如何制定更通用的解决方案,以便多个孩子可以发送事件来更新菜单?

标签: angular

解决方案


通过服务进行的通信使其完全通用。这不仅限于父子通信,还包括任意 2 个组件之间的通信:

文档在这里 - https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

基本上,想要发送数据的组件将数据发送到服务方法。然后服务next(data)向主题发出 ( )。订阅该主题的任何内容都会收到数据。

这些天,您可以使用以下方式在根级别提供服务:

@Injectable({
  providedIn: 'root'
})

无需在您的提供程序数组中列出它。我认为这只是Angular 6。然后按需加载服务。或者,您可以在提供程序数组中提供服务。

如果您想获得更多技术信息,请查看提供全球商店解决方案的ngrx 。


推荐阅读