25 lines
672 B
TypeScript
25 lines
672 B
TypeScript
import { Injectable, NgZone, inject, signal } from '@angular/core';
|
|
|
|
@Injectable({ providedIn: 'root' })
|
|
export class OnlineStatusService {
|
|
private readonly zone = inject(NgZone);
|
|
readonly online = signal(this.readOnlineState());
|
|
|
|
constructor() {
|
|
if (typeof window === 'undefined') {
|
|
return;
|
|
}
|
|
|
|
window.addEventListener('online', () => this.setOnline(true));
|
|
window.addEventListener('offline', () => this.setOnline(false));
|
|
}
|
|
|
|
private setOnline(online: boolean): void {
|
|
this.zone.run(() => this.online.set(online));
|
|
}
|
|
|
|
private readOnlineState(): boolean {
|
|
return typeof navigator === 'undefined' ? true : navigator.onLine;
|
|
}
|
|
}
|