Network status
@flyze/lib-core-angular 1.0.0-alpha.34· latestNetworkStatusService reports whether the browser currently has a network connection, as both a
snapshot and a stream.
service.networkAvailable; // boolean, right nowservice.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.
How it works
Section titled “How it works”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), sonetworkAvailable$never emits the same state twice in a row. Combined with theBehaviorSubject, 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.
What it does not tell you
Section titled “What it does not tell you”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.
Overlap with PwaService
Section titled “Overlap with PwaService”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.