在整个Angular应用程序中发射和广播事件 [英] Emit and broadcast events throughout application in Angular

查看:71
本文介绍了在整个Angular应用程序中发射和广播事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以在angular2中发出可以在整个应用程序中侦听的事件?就像我们在AngularJS中使用$rootScope.broadcastemit一样.在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事件,如

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆