Search code examples
angularscrollinfinite-scroll

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


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

I don't want to polute any of my components, since the awareness of scroll should be injected in several other services... Currently i have following code that compiles, but does not work somehow.

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();

    }
  }
}

Similar code works i Component as desired. Any ideas how to get it run in a service? or something similar?


Solution

  • You cannot have a HostListener in a service. Use the classic:

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