I have inserted a service component (component A) via dependency injection, and this service component A is not inside the template of component B.
How can I catch an event emitted from the service component - how to catch it inside parent component (component B)? I already put the emitting command inside child component like so:
@Output() hostReady = new EventEmitter();
and I am emitting the event like so:
hostReady.emit();
What do I need to do in order to catch it in parent?
Well, since I haven't posted my solution before, I might as well do it now. So, what I did is I had a pattern Subscriber implemented. All of the components that want to know about an event are subscribed to it, and when an event is triggered they know about it. The solution deals with rxjs objects:
import { Subject } from 'rxjs/Subject';
I have a special component intercommService
that declares an event as an rxjs Subject, like this:
selectedLanguage: Subject<string>;
constructor() {
this.selectedLanguage = new Subject<any>();
}
Then, every component (that also has this dependency injected) can trigger the event, using this:
this.intercomm.selectedLanguage.next(language);
And each subscriber component will have this as its subscription to that event, ie, in constructor, a subscriber will have that dependency injected, and will observe its event:
constructor(private intercomm: IntercommService) {
this.intercomm.selectedLanguage.asObservable().subscribe((value: any) => {
// Do something with value
});
}
There are different ways to do it.
have a look in the cookbook examples.
https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#child-to-parent
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With