All files / app/services/windowResizeService window-resize.service.ts

100% Statements 8/8
100% Branches 2/2
100% Functions 2/2
100% Lines 8/8

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 40 41 42                      1x                         246x   246x 244x   41x 41x 41x           2x        
import { 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 window width and
 * height value each time the resize event fires.
 */
@Injectable({
  providedIn: 'root',
})
export class WindowResizeService {
  /**
   * Observable emitting the window width and height value each time the resize
   * event fires.
   */
  resize: Observable<number[]>;
 
  /**
   * Window resize service constructor
   *
   * @param platformId The platform ID
   */
  constructor(
    @Inject(PLATFORM_ID) private platformId: Record<string, unknown>
  ) {
    if (isPlatformBrowser(this.platformId)) {
      this.resize = fromEvent(window, 'resize').pipe(
        map(() => {
          const x = window.innerWidth;
          const y = window.innerHeight;
          return [x, y];
        }),
        share()
      );
    } else {
      //in non-browser environments, provide an empty observable so you can safely subscribe to scroll$
      this.resize = EMPTY;
    }
  }
}