Skip to content

Network status

@flyze/lib-core-angular 1.0.0-alpha.34· latest

NetworkStatusService reports whether the browser currently has a network connection, as both a snapshot and a stream.

service.networkAvailable; // boolean, right now
service.networkAvailable$; // Observable<boolean>

Provided by NetworkModule (network.module.ts:12) — not providedIn: 'root'. Import the module (or provide the service directly) or injection fails. Because it is a plain provider, importing NetworkModule in two lazy modules yields two independent instances, each with its own listeners.

A BehaviorSubject seeded from navigator.onLine, fed by the browser’s online and offline events merged into one stream (network-status.service.ts:29):

merge(
fromEvent(window, 'offline').pipe(map(() => false)),
fromEvent(window, 'online').pipe(map(() => true))
).pipe(startWith(navigator.onLine), this._unsubscriber.takeUntil());

Two details:

  • The subscription is a field initializer, so it starts before the constructor body — the service is listening from the moment it is created, and there is nothing to call to start it.
  • The subscriber drops values equal to the current one (network-status.service.ts:35), so networkAvailable$ never emits the same state twice in a row. Combined with the BehaviorSubject, a late subscriber gets the current state immediately and then only changes.

ngOnDestroy completes the Unsubscriber, which tears the event listeners down through takeUntil. Since the service is module-provided, that actually runs when the providing injector is destroyed.

navigator.onLine and its events describe the network interface, not reachability. A device connected to a Wi-Fi network with no internet access reports true. Treat this as “the browser thinks it is connected”, and use a real request when reachability matters.

PwaService maintains its own networkAvailable$ from the same two events (pwa.service.ts:53) instead of injecting this service, and seeds it with a hardcoded true. An app importing both has two independent trackers; prefer this one — see pwa.