All files / app/services/windowScrollService window-scroll.service.ts

100% Statements 7/7
100% Branches 4/4
100% Functions 2/2
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39                      1x                     246x 246x   246x 244x   56x           2x        
import { DOCUMENT, isPlatformBrowser } from '@angular/common';
import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { EMPTY, Observable, fromEvent, map, share } from 'rxjs';
 
/**
 * Service responsible for providing an observable emitting the scroll value
 * each time the scroll event fires.
 */
@Injectable({
  providedIn: 'root',
})
export class WindowScrollService {
  /** Observable emitting the scroll value each time the scroll event fires. */
  scroll: Observable<number>;
 
  /**
   * Window scroll service constructor
   *
   * @param document The document
   * @param platformId The platform ID
   */
  constructor(
    @Inject(DOCUMENT) private document: Document,
    @Inject(PLATFORM_ID) private platformId: Record<string, unknown>
  ) {
    if (isPlatformBrowser(this.platformId)) {
      this.scroll = fromEvent(window, 'scroll').pipe(
        map(() => {
          return window.scrollY || this.document.documentElement.scrollTop;
        }),
        share()
      );
    } else {
      //in non-browser environments, provide an empty observable so you can safely subscribe to scroll$
      this.scroll = EMPTY;
    }
  }
}