使用服务侦听Angular中的DOM事件 [英] Using service to listen for DOM events in Angular

查看:180
本文介绍了使用服务侦听Angular中的DOM事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Angular 4应用程序中有一个通用弹出窗口组件,为了正确处理弹出窗口显示,我需要监听document上的全局单击事件.

I have a generic pop-up component in my Angular 4 application and in order to correctly handle popup display I need to listen for global click events on the document.

应用程序中可能同时存在许多弹出组件,当用户单击这些组件之外的某个位置时,我需要关闭它们.出于明显的原因,我不应该从组件本身绑定到document:click事件(应该只有一个侦听器),因此我决定创建一个集中式服务,该服务将侦听文档中的全局DOM事件并命令弹出组件.

There could be many pop-up components at the same time in the application and I need to close them when user clicks somewhere outside of the those components. I shouldn't bind to document:click event from the component itself for obvious reasons (there should be only one listener), so I've decided to create a centralized service, which would listen for global DOM events on the document and to command the pop-up components.

初始化弹出组件时,它会在服务中注册自己,并在销毁它时注销自己.因此,该服务始终具有应用程序中所有弹出组件的列表.到目前为止,效果很好.

When pop-up component is initialized, it registers itself with the service and when it's destroyed it deregisters itself. So, the service always has a list of all pop-up components in the application. So far it works great.

但是,我尝试注入 Renderer2 到我的集中式服务,以便通过

However, I've tried to inject the Renderer2 to my centralized service in order to listen for DOM events via it's listen() method, but it looks like it's only available for component injection, not for service injection.

此外,@HostListener('document:click')装饰器在服务中不起作用.

Also, the @HostListener('document:click') decorator is not working in services.

我的架构正确吗?服务监听DOM事件是否是个坏主意?

另一种可能的解决方案是创建另一个组件而不是服务,但是我不喜欢这种方法,因为与自动创建的服务相比,它要求将其手动添加到应用程序中.

The other possible solution would be to create another component instead of the service, but I don't like this approach, because it will require it's manual addition to the application somewhere in contrast with service which is automatically created.

实施我的使用场景的最佳方法是什么?

推荐答案

您应使用Observable.fromEvent

示例插件: https://plnkr.co/edit/tpl:AvJOMERrnz94ekVua0u5

创建与此服务类似的服务:

Create a service similar to this one:

@Injectable()
export class DocService {
  obs: Observable;

  constructor(){
    this.obs = Observable.fromEvent(document, 'click');
  }

  onClick(): Observable{
    return this.obs;
  }
}

然后订阅您组件中的可观察对象:

then subscribe to the observable in your component:

// here I just log the event, in your case, you close the popoup
this.docService.onClick().subscribe(console.log, console.log);

您可能需要确保点击不会在弹出窗口中显示.您可以处理这是您的订阅方法.

you'll probably need to make sure the click is not hapening on your popup. You can handle this is your subscribe method.

这篇关于使用服务侦听Angular中的DOM事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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