I agree that your idea of ββobservable service is your best option here (like the others), although I would prefer BehaviorSubject in this case. Here is a simple, working plunkr demonstrating how you could implement this:
https://plnkr.co/edit/quHc2yOkxXIbXYUlnZbB?p=preview
If we break this requirement, you will need an event proxy service that simply passes the event. This plunkr can also pass a parameter object through a service - in case you need to do this, but if not, just pass in any object you want (or just remove the param arguments from all the methods).
This implementation does not take care that the components are not siblings, because we use the service. Both will be provided with the same service instance regardless of the structure of your application.
For a quick reference, code snippets are important here:
EventProxyService
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; @Injectable() export class EventProxyService { private eventSubject = new BehaviorSubject<any>(undefined); triggerSomeEvent(param: any) { this.eventSubject.next(param); } getEventSubject(): BehaviorSubject<any> { return this.eventSubject; } }
Firstcompponent
import { Component, OnInit } from '@angular/core'; import { EventProxyService } from './event-proxy.service'; @Component({ selector: 'app-first', templateUrl: './src/first.component.html' }) export class FirstComponent implements OnInit { displayText = 'I havent created any events yet.'; constructor(private eventProxyService: EventProxyService) { } ngOnInit() { } triggerAnEvent() { this.eventProxyService.triggerSomeEvent(Date()); this.displayText = 'I fired an event.' } }
SecondComponent
import { Component, OnInit } from '@angular/core'; import { EventProxyService } from './event-proxy.service'; @Component({ selector: 'app-second', templateUrl: './src/second.component.html' }) export class SecondComponent implements OnInit { displayText = 'I havent got an event yet'; constructor(private eventProxyService: EventProxyService) { } ngOnInit() { this.eventProxyService.getEventSubject().subscribe((param: any) => { if (param !== undefined) { this.theTargetMethod(param); } }); } theTargetMethod(param) { this.displayText = 'Target Method got called with parameter: "' + param + '"'; } }
source share