user3097695
user3097695

Reputation: 1284

Detection of "online" and "offline" angular 8

I have the following service for checking network connection:

export class InternetService {
public connectionChanged = new BehaviorSubject<boolean>(false);
public connState =  true;
constructor(private apiService: ApiService) {
    if (navigator.onLine)
        this.statusChanged(true);
    else
        this.statusChanged(false);
    this.addEventListeners();
}
private addEventListeners() {
    window.addEventListener('online', () => this.statusChanged(true));
    window.addEventListener('offline', () => this.statusChanged(false));
}

testConnection() {
    this.apiService.callMyMethod().subscribe(res => {
        this.connected(true);
    }, error => {
        this.connected(false);
    });
}
statusChanged(connected: boolean) {
    if (connected) {
        this.testConnection();
    } else {
        this.connected(false);
    }
}
connected(data: boolean) {
    this.connState = data;
    this.connectionChanged.next(this.connState);
}
}

Code functions work well on Edge Browser, but not on Chrome. I understand there is a problem with Chrome according to the following reference:

https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine

In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking.

Basically, on chrome:

(1) navigator.onLine always returns true; (2) when I disconnected or reconnect WiFi, the two "onLine" or "offLine" events do not do anything.

Is there an alternative way to have events when the WiFi is disconnected or reconnected?

Upvotes: 2

Views: 1678

Answers (1)

Rameez Rami
Rameez Rami

Reputation: 5728

Online/offline detection cannot be 100% accurately decided because network status can vary for a number of reasons.

Still, if you want an implementation of the same with Angular+NGRX, You can find more details here.

https://hackernoon.com/using-angular-to-detect-network-connection-status-onlineoffline

import { Component, OnDestroy, OnInit, VERSION } from '@angular/core';

import { fromEvent, merge, of, Subscription } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  networkStatus: boolean = false;
  networkStatus$: Subscription = Subscription.EMPTY;

  constructor() {}

  ngOnInit(): void {
    this.checkNetworkStatus();
  }

  ngOnDestroy(): void {
    this.networkStatus$.unsubscribe();
  }

  checkNetworkStatus() {
    this.networkStatus = navigator.onLine;
    this.networkStatus$ = merge(
      of(null),
      fromEvent(window, 'online'),
      fromEvent(window, 'offline')
    )
      .pipe(map(() => navigator.onLine))
      .subscribe(status => {
        console.log('status', status);
        this.networkStatus = status;
      });
  }
}

You can see the demo here.

or check the code here

Happy coding!!! 🎉🎉🎉

Upvotes: 0

Related Questions