How to get internet status in Angular App
Web applications need to be aware of the user's internet connectivity. By knowing whether the user is online or offline, you can provide a better user experience and handle network-related tasks accordingly. In this article, we'll explore how to get the internet status in an Angular app using a service file.
import { Injectable } from '@angular/core';
import { of, fromEvent, merge, map } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class NetworkStatusService {
status$ = merge(
of(navigator.onLine),
fromEvent(window, 'online').pipe(map(() => true)),
fromEvent(window, 'offline').pipe(map(() => false))
);
}
The NetworkStatusService
class contains a status$
property that is an Observable representing the internet status. It combines three sources of information to determine the status:
of(
navigator.onLine
)
: This creates an Observable that emits the current online status of the browser. It will emittrue
if the browser is online andfalse
if it's offline.fromEvent(window, 'online')
: This creates an Observable that listens for theonline
event on thewindow
object. When the browser goes online, it emitstrue
.fromEvent(window, 'offline')
: Similarly, this creates an Observable that listens for theoffline
event on thewindow
object. When the browser goes offline, it emitsfalse
.
By merging these three sources, the status$
Observable will emit the current internet status and update whenever the status changes.
the Example app:
https://stackblitz.com/edit/stackblitz-starters-thscwg?file=src%2Fnetwork-status.service.ts
Thanks to Sinan Ozturk. He handled the task. i just wrote a note for the future as reminder