是否可以在简单服务中使用 Angular @HostListener('window:scroll',) 而不是组件或指令

Is it possible to have Angular @HostListener('window:scroll',) in simple Service not Component or Directive

是否可以在简单服务中使用 Angular @HostListener('window:scroll',) 而不是组件或指令代码?

我不想污染我的任何组件,因为应该在其他几个服务中注入滚动意识...目前我有以下编译代码,但不知何故不起作用。

import { Component, OnInit, Injectable, Inject, HostListener } from '@angular/core';
import { SearchService } from './search.service';
import { DOCUMENT } from '@angular/platform-browser';

const scrollStepToReload = 3700;

@Injectable()
export class ScrollWatcherService {

  private maxReachedScroll = 0;
  private lastLoadedAt = 0;

  constructor(private searchService: SearchService, @Inject(DOCUMENT) private document: any) { }

  @HostListener('window:scroll', ['$event'])
  onScroll($event) {

    const scrollOffset = window.pageYOffset || this.document.documentElement.scrollTop || this.document.body.scrollTop || 0;
    console.debug("Scroll Event", scrollOffset);

    if (scrollOffset > this.maxReachedScroll) {
      this.maxReachedScroll = scrollOffset;
    }
    if (this.lastLoadedAt + scrollStepToReload < this.maxReachedScroll) {

      this.lastLoadedAt = this.maxReachedScroll;
      this.searchService.continueSearch();

    }
  }
}

类似的代码可以根据需要在组件中运行。 任何想法如何在服务中获得它 运行?或类似的东西?

服务中不能有 HostListener。使用经典:

window.addEventListener('scroll', () => { console.log('scrolling'); });