node.jsangularrxjsobservable

Raise an event on a shared Observable


In my Angular app, I have a parent component with two child components. I want to share an observable, call it newUploadStarted$, created in the parent component that the two child components and communicate on. The two child components are multiple instances of the same component that, if clicked, trigger a file upload. I want to raise an event on newUploadStarted$ in the child component such that all child events react to it by clearing old messages they might have.

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.
       
    }

To me, this should be something very simple to do, but I'm just not seeing an example of this in a way that makes sense to me. What am I missing?


Solution

  • Try using a Subject instead of an Observable as a communication bus between your parent and children components.

    A Subject will let you multicast any values across all observers.

    newUploadStarted$.next();
    

    If you find that you need to share the same bus across children of different parents, you may want to consider relocating it to a service.