Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emitting events globally

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?

like image 203
Geoff Avatar asked Jul 04 '17 10:07

Geoff


People also ask

What are emit events?

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.

Which of the following is the commonly used events in EventEmitter?

Event: 'error' When an error occurs within an EventEmitter instance, the typical action is for an 'error' event to be emitted.

How do I use EventEmitter?

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.

What is returned by emitter on event listener method?

listenerCount(emitter, event) Returns the number of listeners for a given event.


2 Answers

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")
      }
 }
like image 175
Milad Avatar answered Sep 30 '22 05:09

Milad


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.

like image 24
eddyP23 Avatar answered Sep 30 '22 05:09

eddyP23