5

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?

Maciej Treder
  • 11,866
  • 5
  • 51
  • 74
Geoff
  • 6,277
  • 23
  • 87
  • 197

2 Answers2

4

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")
      }
 }
Milad
  • 27,506
  • 11
  • 76
  • 85
  • You should not use `EventEmitter` inside your services; https://stackoverflow.com/questions/36076700/what-is-the-proper-use-of-an-eventemitter. Use an `Observable`/`Subject` instead. – eko Jul 04 '17 at 10:53
1

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.

eddyP23
  • 6,420
  • 7
  • 49
  • 87
  • For global events in angular 2, you may want to look at this: https://modewagon.wordpress.com/2017/09/12/angular2-4-global-events/ might help – Victor Odiah Sep 12 '17 at 14:57