首页 > 解决方案 > 如何将数据从 app.component 发送到其他(子)组件

问题描述

我正在使用 Angular 6。我想将数据(我从外部 API 获取)从 app.component 发送到其他(子)组件,我不想在所有组件中分别并重复调用该公共 API/服务。我想调用一次,所以我在 app.component.ts 中调用

这是一个服务/API代码

this.mainService.getBaseModel().subscribe(ret => {
        this.basemodel = ret;
    }, error => { }, () => {
});

我想在我的应用程序的所有组件中发送这个“basemodel”值。帮助我更好地解决和理解它。谢谢你。

标签: angulartypescriptasp.net-web-apiangular-components

解决方案


有两种方法可以实现这一点,

  1. @Input,这样我们就可以将数据传递给每个child componentfrom parent component
  2. 为所有这些创建一个公共服务,然后使用服务方法获取对象

如果你有一个或两个组件来共享来自 Parent 的数据,那么使用 @Input否则 Service 与最新的 RxJs 类BehaviourSubjectSubject等)可能真的很容易。

如果您想关注@Input,请关注这篇文章 -将@input 数据传递给孩子

遵循此服务与 BehaviourSubject - https://medium.com/@weswhite/angular-behaviorsubject-service-60485ef064fc


推荐阅读