如何将数据从app.component发送到其他(子)组件

时间:2019-11-28 15:33:59

标签: angular typescript asp.net-web-api angular-components

我正在使用angular6。我想将数据(从外部API获取)从app.component发送到其他(子)组件,我不想在所有组件中分别调用该通用API /服务,反复地。我想调用一次,所以这就是为什么我要调用app.component.ts

这是服务/ API代码

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

我想在我的应用程序中的所有组件之间发送此“基本模型”值。帮助我更好地解决和理解它。谢谢。

3 个答案:

答案 0 :(得分:3)

有两种方法可以实现,

  1. @Input,我们可以将数据从child component传递到每个parent component
  2. 为所有这些创建通用服务,然后使用服务方法获取对象

如果您有一个或两个要与父级共享数据的组件,则使用@ Input,否则使用具有最新 RxJs类的服务BehaviourSubjectSubject,等。)可能真的很容易。

如果您想关注@Input,请关注此帖子-pass @input data to child

针对BehaviourSubject-https://medium.com/@weswhite/angular-behaviorsubject-service-60485ef064fc

答案 1 :(得分:0)

在不了解应用程序结构的情况下,很难说出使用哪种方法。 您可以使用:

    {li> @Input()@Output()的组合
  • 另一种保存和分发数据的服务
  • 像ngrx这样的商店

答案 2 :(得分:0)

在Angular官方文档中,您可以找到几种解决方法。它们可以在这里找到:https://angular.io/guide/component-interaction#pass-data-from-parent-to-child-with-input-binding

这里也有上述方法的实时示例: https://stackblitz.com/angular/plpgkjondrl