在我的 Angular 应用程序中,我有一个父组件和两个子组件。我想共享一个可观察对象,称之为
newUploadStarted$
,在父组件中创建,两个子组件在其上进行通信。这两个子组件是同一组件的多个实例,如果单击它们,则会触发文件上传。我想在子组件中的 newUploadStarted$ 上引发一个事件,以便所有子事件通过清除它们可能拥有的旧消息来对其做出反应。
export class ReportUploaderComponent implements OnInit {
@Input() newUploadStarted$: Observable<1>;
...
onChooseBlueReportFile(files: FileList) {
newUploadStarted$.raiseEvent(1); // Specific number isn't as important as letting the child raise the event on something it did not create.
}
对我来说,这应该是一件非常简单的事情,但我只是没有以对我来说有意义的方式看到这样的例子。我错过了什么?
Subject
而不是 Observable
作为父组件和子组件之间的通信总线。
A
Subject
可以让您在所有观察者之间多播任何值。
newUploadStarted$.next();
如果您发现需要在不同父母的孩子之间共享同一辆巴士,您可能需要考虑将其重新定位到服务。