是否可以在服务中使用HostListener?或者如何在Angular服务中使用DOM事件? [英] Is it possible to use HostListener in a Service? Or how to use DOM events in an Angular service?
问题描述
我想创建一个服务,该服务可检测所有键盘输入,基于可配置的映射将按键转换为动作,并公开各种元素可以绑定以对特定按键做出反应的可观察对象.
I want to create a service which detects all keyboard input, translates the key strokes into actions based on a configurable mapping, and exposes observables which various elements can bind to to react to specific key presses.
以下是到目前为止我的代码的简化,它在HostListener处于组件中时有效,但是现在我将其移入了一个服务,即使它已被初始化也永远不会触发.不可能在服务中检测到这样的输入吗?
The following is a simplification of my code so far, it worked when HostListener was in a component, but now I've moved it into a service it never fires even though it is definitely initialised. Is it not possible to detect input like this in a service?
import { Injectable, HostListener } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class InputService {
@HostListener('window:keydown', ['$event'])
keyboardInput(event: any) {
console.log(event);
}
}
推荐答案
似乎无法在服务中使用HostListener
.
Seems like its not possible to use HostListener
in a service.
更新
就像 实时演示: https://stackblitz.com/edit/angular-so4?file=src%2Fapp%2Fmy-mouse.service.ts OLD 您可以像@yurzui所指出的那样使用 You could use the old way https://plnkr.co/edit/tc53cvQDfLHhaR68ilKr?p=preview 这篇关于是否可以在服务中使用HostListener?或者如何在Angular服务中使用DOM事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!Stanislasdrg Reinstate Monica
所述,使用
window.addEventListener
的旧方法.window.addEventListener
like @yurzui pointed out already.import {Component, NgModule, HostListener, Injectable} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Injectable()
export class MyService {
constructor() {
window.addEventListener('keydown', (event) => {
console.dir(event);
});
}
}
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
`,
})
export class App {
constructor(private _srvc: MyService) {
this.name = 'Angular2'
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
providers: [MyService],
bootstrap: [ App ]
})
export class AppModule {}