2

Is there a way to emit event in angular2 that can be listened to in entire application? Like we had in AngularJS using $rootScope.broadcast and emit. Can this same thing be achieved in angular2? I read about @Output() and EventEmitter() and implemented it but it restricts only the parent to listen to the event emmitted by child.

I read about BehaviorSubject being one of the ways to do this. Is that the right approach? Any other solution for this?

JS dev
  • 8,456
  • 12
  • 68
  • 111
  • 3
    Using observables seems to be a good option: http://stackoverflow.com/questions/34376854/delegation-eventemitter-or-observable-in-angular2/35568924#35568924 – j3r6me Nov 30 '16 at 13:17
  • You can add an observable to your parent that get's set when the child emits. You can then subscribe to that observable anywhere you want. – John Baird Nov 30 '16 at 13:18

1 Answers1

2

In Angular2 there is no global scope. There are only components and services.

With services you can define their scope by the place you provide them. If you provide one in @NgModule({providers: ...}) (or in an imported module) it becomes globally avialable. If you provide it at a component, it is only available to this component and its children.

For examples how to use shared services see https://github.com/dart-lang/sdk/issues/27637

You can also dispatch a bubbling DOM event like shown in in Angular2 how to know when ANY form input field lost focus

Events emitted with @Output() someOutput:EventEmitter = new EventEmitter(); don't bubble.

Community
  • 1
  • 1
Günter Zöchbauer
  • 490,478
  • 163
  • 1,733
  • 1,404
  • 2
    `BehaviorSubject` is an easy way. Hardcore reactivionists think that `Subject` should be avoided. http://davesexton.com/blog/post/To-Use-Subject-Or-Not-To-Use-Subject.aspx, http://stackoverflow.com/questions/14396449/why-are-subjects-not-recommended-in-net-reactive-extensions So this is an opinionated question. If you are new to rxjs I'd suggest you use it until you are more comfortable with reactive programming and you are able to decide for yourself. – Günter Zöchbauer Dec 01 '16 at 09:05
  • 1
    Thanks Gunter!! I shall do it. Just wanted to confirm for my knowledge Is services the best way to do it? – JS dev Dec 01 '16 at 09:11
  • Services is **the** way to do it in Angular2. – Günter Zöchbauer Dec 01 '16 at 09:14