我正在使用angular6。我想将数据(从外部API获取)从app.component发送到其他(子)组件,我不想在所有组件中分别调用该通用API /服务,反复地。我想调用一次,所以这就是为什么我要调用app.component.ts
这是服务/ API代码
this.mainService.getBaseModel().subscribe(ret => {
this.basemodel = ret;
}, error => { }, () => {
});
我想在我的应用程序中的所有组件之间发送此“基本模型”值。帮助我更好地解决和理解它。谢谢。
答案 0 :(得分:3)
有两种方法可以实现,
@Input
,我们可以将数据从child component
传递到每个parent component
。如果您有一个或两个要与父级共享数据的组件,则使用@ Input
,否则使用具有最新 RxJs类的服务(BehaviourSubject
,Subject
,等。)可能真的很容易。
如果您想关注@Input,请关注此帖子-pass @input data to child
针对BehaviourSubject-https://medium.com/@weswhite/angular-behaviorsubject-service-60485ef064fc
答案 1 :(得分:0)
在不了解应用程序结构的情况下,很难说出使用哪种方法。 您可以使用:
@Input()
和@Output()
的组合
答案 2 :(得分:0)
在Angular官方文档中,您可以找到几种解决方法。它们可以在这里找到:https://angular.io/guide/component-interaction#pass-data-from-parent-to-child-with-input-binding
这里也有上述方法的实时示例: https://stackblitz.com/angular/plpgkjondrl