Worldwide Event Releases

What I'm trying to achieve is the desire to create my own event in angular2 globally and listen to several components of it, so that not only the parent-child pattern

In my source component of the event, 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 receive this event

 export class CmpTwoComponent{ //here get the emitted event with data } 

How to achieve the above?

+5
source share
2 answers

You can use the general service for this.

 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 sharedService will be

 @Injectable() export class SharedService{ public testev = new Subject() } 

Obviously, if you still need Output so that the parent component can subscribe normally, you can also add this:

 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") } } 
+3
source

There is no template in Angular that allows you to achieve what you ask for.

The best option I can come up with for you would be to create a custom service. Add some services that you enter into the AppComponent (hence having one instance of the service). In the Service, you can have any logic that you need.

+1
source

Source: https://habr.com/ru/post/1269480/


All Articles