Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch event emitted from service injected into component

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?

like image 443
Vladimir Despotovic Avatar asked Feb 04 '23 22:02

Vladimir Despotovic


2 Answers

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
    });
}
like image 61
Vladimir Despotovic Avatar answered Feb 07 '23 11:02

Vladimir Despotovic


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

like image 22
Roninio Avatar answered Feb 07 '23 11:02

Roninio