问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/40889320/emit-and-broadcast-events-throughout-application-in-angular