【发布时间】:2020-12-04 16:21:56
【问题描述】:
我正在开发的网站有一个主要组件,我正试图使其可重用。是这样的:
-> parent
parent.component.html
parent.component.scss
parent.component.ts
-> child_1
child_1.component.html
child_1.component.scss
child_1.component.ts
-> child_2
child_2.component.html
child_2.component.scss
child_2.component.ts
(...)
-> services
-> parent-services
parent.service.ts
parent.service.ts 有 http 方法,但我需要在 child_1.component.ts 和 child_2.component.ts 中返回一个 http 请求,以便将来自该请求的数据订阅到可重用变量。
如何在一个服务请求中获取数据,然后订阅一次来填充我的 html 页面,该页面将用于 child_1.component.ts 和 child_2.component.ts以不同的方式?
*Obs.:在订阅期间我做了一些数据操作,比如验证它是否为 null 然后添加一些默认值,然后复制粘贴这个块代码似乎不是一个好的解决方案。
【问题讨论】:
-
这个解决方案对我没有帮助:stackoverflow.com/questions/45201555/…
-
当它准备好时,您可以订阅并从父组件向 child_1 和 child_2 发送 http 响应。
-
不错!一段时间后,我了解了如何处理相关和不相关组件之间的数据(并非总是适用 EventEmitter)。很棒的教程可以在这里找到:fireship.io/lessons/…
标签: angular typescript service observable