在 Angular 的整个应用程序中发出和广播事件 [英] Emit and broadcast events throughout application in Angular
问题描述
有没有办法在 angular2 中发出可以在整个应用程序中收听的事件?就像我们在 AngularJS 中使用 $rootScope.broadcast
和 emit
一样.在angular2中可以实现同样的事情吗?我阅读了 @Output()
和 EventEmitter()
并实现了它,但它只限制父级监听子级发出的事件.
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.
我了解到 BehaviorSubject
是实现此目的的方法之一.这是正确的方法吗?对此还有其他解决方案吗?
I read about BehaviorSubject
being one of the ways to do this. Is that the right approach? Any other solution for this?
推荐答案
在 Angular2 中没有全局作用域.只有组件和服务.
In Angular2 there is no global scope. There are only components and services.
通过服务,您可以通过提供服务的位置来定义其范围.如果您在 @NgModule({providers: ...})
(或在导入的模块中)提供一个,它就可以在全球范围内使用.如果您在组件中提供它,则它仅可用于该组件及其子组件.
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.
有关如何使用共享服务的示例,请参见 https://github.com/dart-lang/sdk/issues/27637
For examples how to use shared services see https://github.com/dart-lang/sdk/issues/27637
您还可以调度一个冒泡 DOM 事件,如 在 Angular2 中如何知道任何表单输入字段何时失去焦点
You can also dispatch a bubbling DOM event like shown in in Angular2 how to know when ANY form input field lost focus
使用 @Output() someOutput:EventEmitter = new EventEmitter();
发出的事件不会冒泡.
Events emitted with @Output() someOutput:EventEmitter = new EventEmitter();
don't bubble.
这篇关于在 Angular 的整个应用程序中发出和广播事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!