Reputation: 16959
I have the following structure: app.component.html holds the following components:
<componentA>
<router-outlet></router-outlet>
I inject componentB into the router outlet and componentB has its own router outlet.
<componentB><router-outlet></router-outlet></componentB>
I inject componentC inside ComponentB´s router outlet
<componentC>
I want to send an event from ComponentA to ComponentC.
I am trying to use a service to accomplish this by injecting it into ComponentA which sends the event and ComponentC is subscribing to the event through the injected service. Component C is not receiving the events.
However if I move componentA inside ComponentB the event is successfully emitted to ComponentC.
How can I emit the event from ComponentA to ComponentC when ComponentA is located at the root in app.component.html?
[UPDATE]
I followed the example on bidirectional service but the event is still not received. Here is the code:
My Service:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class MyService {
private mySource = new Subject<string>();
source$ = this.mySource.asObservable();
sendEvent(stringParam: string) {
this.mySource.next(stringParam);
}
}
Component A sends the event
this.myService.sendEvent("test");
Component C subscribes and listens for the event
this.subscription = this.myService.source$.subscribe(stringParam => {
console.log('Received event: ' + stringParam);
});
I am using Angular RC5. Any idea what I am missing?
Upvotes: 5
Views: 9068
Reputation: 658057
At first, the router doesn't add components into the <router-outlet>
but makes it a sibling. This is because of how ViewContainerRef.createComponent
works.
Events sent from EventEmitter
also don't bubble and therefore can only be used to add event handlers on child elements using (event)="doSomething()"
.
A shared service is usually the right thing to use in your situation. For more details see https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
Upvotes: 8