angular - 如何将数据从 app.component 发送到其他(子)组件
问题描述
我正在使用 Angular 6。我想将数据(我从外部 API 获取)从 app.component 发送到其他(子)组件,我不想在所有组件中分别并重复调用该公共 API/服务。我想调用一次,所以我在 app.component.ts 中调用
这是一个服务/API代码
this.mainService.getBaseModel().subscribe(ret => {
this.basemodel = ret;
}, error => { }, () => {
});
我想在我的应用程序的所有组件中发送这个“basemodel”值。帮助我更好地解决和理解它。谢谢你。
解决方案
有两种方法可以实现这一点,
@Input
,这样我们就可以将数据传递给每个child component
fromparent component
。- 为所有这些创建一个公共服务,然后使用服务方法获取对象
如果你有一个或两个组件来共享来自 Parent 的数据,那么使用 @Input
否则 Service 与最新的 RxJs 类(BehaviourSubject
,Subject
等)可能真的很容易。
如果您想关注@Input,请关注这篇文章 -将@input 数据传递给孩子
遵循此服务与 BehaviourSubject - https://medium.com/@weswhite/angular-behaviorsubject-service-60485ef064fc
推荐阅读
- flutter - 在 Flutter 中创建底部导航栏类
- mysql - Symfony Doctrine 运行相同的查询
- javascript - 如何将 html 元素的 Json 对象转换为我可以使用 C# 或 js 或 jquery 在视图上呈现的实际 HTML 元素
- spring-boot - Spring批处理。如何链接具有不同类型的多个itemProcessor?
- javascript - 成员状态命令显示流式传输的人数
- docker - 将 NGINX 反向代理指向主机,而不是指向 docker 容器并获取客户端的真实 IP
- mysql - 牙科诊所数据库设计 - 牙齿问题
- java - 数据表 - colspan 在数据表上未正确显示
- python - 构建的python模块的位置
- python - 如何使用 seaborn 绘制 OPTICS 聚类结果?