angular - 来自多个孩子的输出和发射器
问题描述
我的 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 的模板。如何制定更通用的解决方案,以便多个孩子可以发送事件来更新菜单?
解决方案
通过服务进行的通信使其完全通用。这不仅限于父子通信,还包括任意 2 个组件之间的通信:
文档在这里 - https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service
基本上,想要发送数据的组件将数据发送到服务方法。然后服务next(data)
向主题发出 ( )。订阅该主题的任何内容都会收到数据。
这些天,您可以使用以下方式在根级别提供服务:
@Injectable({
providedIn: 'root'
})
无需在您的提供程序数组中列出它。我认为这只是Angular 6。然后按需加载服务。或者,您可以在提供程序数组中提供服务。
如果您想获得更多技术信息,请查看提供全球商店解决方案的ngrx 。
推荐阅读
- git - 尝试更正我的 GitHub 子模块以将其删除并添加到根文件夹以进行提交
- react-native - React native Expo:创建了一个应用程序,在 chrome 的检查工具中它运行良好,但在移动设备上运行后它被放大了
- python - 如何删除与 pdf 对应文件同名的 excel 文件?
- ruby-on-rails - 如何覆盖 batch_action(ActiveAdmin) 并在那里传递对象?
- apache - .htaccess 将 domain.com/folder 重定向到外部网站而不更改 URL
- javascript - 为什么Element null vue js
- html-email - 来自我服务器的图像无法在 Yahoo、Rediffmail 客户端中加载
- uipath - UIPath - 存在全局处理程序时忽略重试范围
- reactjs - React 组件状态在按钮单击设置后不会改变
- c++ - 将 GTSAM 添加到项目中