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.