更新时间:2023-02-09 21:37:03
在不引入任何其他库的情况下,Angular为组件之间的相互通信指定了几种方法.文档
Without pulling in any other libraries, Angular specifies a few ways for components to talk to each other. Documentation
由于您的组件不是父/子,而是兄弟姐妹,因此选项更加受限制.
Since your components are not parent/child but siblings, the options are even more limited.
根据您显示的代码,我相信#2是您的***选择.因此,您可以将属性添加到您的 CourseService
:
Based on the code you showed, I believe #2 is your best option. So, you can add a property to your CourseService
:
public selectedCourse: ICourse;
然后您可以在两个组件中对其进行访问:
Then you can access it in both components:
this.courseService.selectedCourse;
此方法的问题在于,您必须管理一个伪全局状态,并确保仅将服务注入/提供一次(否则每个组件都将获得其自己的服务实例,并且您无法共享数据).
The issues with this approach are that you then have to manage a psuedo-global state and make sure the the service is only injected/provided once (otherwise each component will get its own instance of the service and you can't share data).
正如Pavan在对该问题的评论中指出的那样,您可能应该使用 Observable
并订阅它.通过上述方法,当值更改时,组件将不会收到通知,并且需要主动检查负载上的更改.
As noted in a comment on the question by Pavan, you should probably use an Observable
and subscribe to it. With the approach mentioned above, the components will not receive notifications when the value changes and will need to proactively check for changes on load.