What am trying to achieve is I would like to emit a custom event in angular2 globally and have multiple components listen to it so not just the parent-child pattern
In my event source component, I have
export class EventSourceComponent{
@Output() testev = new EventEmitter();
onbtnclick(){
this.testev.emit("i have emitted an event")
}
}
Now I would like other components to get this event
export class CmpTwoComponent{
//here get the emitted event with data
}
How do I achieve the above?
An event emitter is a pattern that listens to a named event, fires a callback, then emits that event with a value. Sometimes this is referred to as a “pub/sub” model, or listener. It's referring to the same thing.
Event: 'error' When an error occurs within an EventEmitter instance, the typical action is for an 'error' event to be emitted.
Simply use it to emit events from your component. Take a look a the following example. @Component({ selector : 'child', template : ` <button (click)="sendNotification()">Notify my parent! </button> ` }) class Child { @Output() notifyParent: EventEmitter<any> = new EventEmitter(); sendNotification() { this.
listenerCount(emitter, event) Returns the number of listeners for a given event.
You could use a shared service for that.
export class EventSourceComponent{
constructor(private sharedService : SharedService){}
onbtnclick(){
this.sharedService.testev.next("i have emitted an event")
}
}
export class CmpTwoComponent{
//here get the emitted event with data
constructor(sharedService : SharedService){
sharedService.testev.subscribe((event)=>{console.log(event)})
}
}
and then the sharedService would be
@Injectable()
export class SharedService{
public testev = new Subject()
}
Obviously, if you still need the Output
so the parent component could be able to subscribe normally, you could add that too :
export class EventSourceComponent{
@Output() testev = new EventEmitter();
constructor(private sharedService : SharedService){}
onbtnclick(){
this.testev.emit("i have emitted an event")
this.sharedService.testev.next("i have emitted an event")
}
}
There is no pattern in Angular that allows to achieve what you ask for.
The best option that I can think of for you would be to create a custom service. Make some service that you inject into AppComponent (therefore having a single instance of the service). In the Service you can have whatever logic you want.
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