似乎在服务中无法使用HostListener
。
更新
正如Stanislasdrg Reinstate Monica
所写,有一种更加优雅且更加Angular的方式,使用renderer。
@Injectable()
export class MyMouseService implements OnDestroy {
private _destroy$ = new Subject();
public onClick$: Observable<Event>;
constructor(private rendererFactory2: RendererFactory2) {
const renderer = this.rendererFactory2.createRenderer(null, null);
this.createOnClickObservable(renderer);
}
ngOnDestroy() {
this._destroy$.next();
this._destroy$.complete();
}
private createOnClickObservable(renderer: Renderer2) {
let removeClickEventListener: () => void;
const createClickEventListener = (
handler: (e: Event) => boolean | void
) => {
removeClickEventListener = renderer.listen("document", "click", handler);
};
this.onClick$ = fromEventPattern<Event>(createClickEventListener, () =>
removeClickEventListener()
).pipe(takeUntil(this._destroy$));
}
}
现场演示:https://stackblitz.com/edit/angular-so4?file=src%2Fapp%2Fmy-mouse.service.ts
OLD
您可以像@yurzui已经指出的那样使用旧的方式window.addEventListener
。
https://plnkr.co/edit/tc53cvQDfLHhaR68ilKr?p=preview
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 {}
window.addEventListener
。 - yurzui