깜놀하는 해므찌로

Angular resize Service 예시 / response width 본문

IT

Angular resize Service 예시 / response width

agnusdei1207 2023. 9. 2. 00:36
반응형
SMALL
import { Injectable, computed, signal } from '@angular/core';
import { BehaviorSubject, Observable, Subject, fromEvent } from 'rxjs';

export enum Platform {
  MOBILE,
  TABLET,
  DESKTOP,
}

@Injectable({
  providedIn: 'root',
})
export class PlatformService {
  private resizeEvent$: Observable<any>;

	// 초기값 : DESKTOP 설정
  public platform$ = new BehaviorSubject<Platform>(Platform.DESKTOP);

  private width = signal<number>(window.innerWidth);

  private isMobile = computed(() => this.width() < 480);
  private isTablet = computed(() => this.width() < 640 && this.width() >= 480);
  private isDesktop = computed(() => this.width() >= 640);

  constructor() {
    this.resizeEvent$ = fromEvent(window, 'resize');

    this.resizeEvent$.subscribe({
      next: () => {
        this.width.set(window.innerWidth);
        this.setPlatform();
      },
    });

    this.setPlatform();
  }

  setPlatform() {
    console.log(this.isMobile(), this.isTablet(), this.isDesktop());
    if (this.isMobile()) {
      this.platform$.next(Platform.MOBILE);
    } else if (this.isTablet()) {
      this.platform$.next(Platform.TABLET);
    } else if (this.isDesktop()) {
      this.platform$.next(Platform.DESKTOP);
    }
  }

  platform() {
    return this.platform$.asObservable();
  }
}



- This line declares a public property named `platform$` with the type `BehaviorSubject<Platform>`.
- `BehaviorSubject` is a type of Observable that stores the current value and emits it to new subscribers.
- The generic parameter `<Platform>` specifies the type of values that will be emitted by the `BehaviorSubject`, in this case, the `Platform` enum.
- `Platform.DESKTOP` is passed as the initial value to the `BehaviorSubject`. It means that the initial platform value is set to `DESKTOP`.

In summary, the `platform$` property is a `BehaviorSubject` that will emit platform values of type `Platform`. It starts with an initial value of `DESKTOP`. Other parts of the code can subscribe to this `BehaviorSubject` to receive updates whenever the platform changes.

반응형
LIST