midhunsivarajan
midhunsivarajan

Reputation: 49

How to check whether there is network connection

How to check if there is network connection in browser....

using angular code....

I need to set up a scenario where the app alerts a message when the connection is offline.The snippet in the forum is said to work fine in mobile devices.How to tweak the code so that it works fine in browser environment too.Any help is appreciated,. I am new to ionic 4.

import { Injectable } from '@angular/core';
import { Network } from '@ionic-native/network/ngx'
import { BehaviorSubject, Observable } from 'rxjs';
import { ToastController, Platform } from '@ionic/angular';

export enum ConnectionStatus {
  Online,
  Offline
}

@Injectable({
  providedIn: 'root'
})
export class NetworkService {

  private status: BehaviorSubject<ConnectionStatus> = new BehaviorSubject(ConnectionStatus.Offline);

  constructor(private network: Network, private toastController: ToastController, private plt: Platform) {
    this.plt.ready().then(() => {
      this.initializeNetworkEvents();
      let status =  this.network.type !== 'none' ? ConnectionStatus.Online : ConnectionStatus.Offline;
      this.status.next(status);
    });
  }

  public initializeNetworkEvents() {

    this.network.onDisconnect().subscribe(() => {
      if (this.status.getValue() === ConnectionStatus.Online) {
        console.log('WE ARE OFFLINE');
        this.updateNetworkStatus(ConnectionStatus.Offline);
      }
    });

    this.network.onConnect().subscribe(() => {
      if (this.status.getValue() === ConnectionStatus.Offline) {
        console.log('WE ARE ONLINE');
        this.updateNetworkStatus(ConnectionStatus.Online);
      }
    });
  }

  private async updateNetworkStatus(status: ConnectionStatus) {
    this.status.next(status);

    let connection = status == ConnectionStatus.Offline ? 'Offline' : 'Online';
    let toast = this.toastController.create({
      message: `You are now ${connection}`,
      duration: 3000,
      position: 'bottom'
    });
    toast.then(toast => toast.present());
  }

  public onNetworkChange(): Observable<ConnectionStatus> {
    return this.status.asObservable();
  }

  public getCurrentNetworkStatus(): ConnectionStatus {
    return this.status.getValue();
  }
}

Upvotes: 0

Views: 1737

Answers (1)

Abhinav Kumar
Abhinav Kumar

Reputation: 3036

In angular, or native javascript, you can use a browser window API event online and offline.

Later you can wrap it in any service with Behaviorsubject

You can use the below event with HostListener decorator in angular to detect online or offline. This works in all major browser including Mobile browsers as well.

  @HostListener("window:online", ["$event"])
  onlineEvent(event) {
    this.processOnline(event);
  }
  processOnline(event){
    if (event.type == "online") {
      // do something here when app is online or become online after gets offline
    }
  }
  @HostListener("window:offline", ["$event"])
  offlineEvent(event) {
    this.processOfflineEvent(event);
  }
  processOfflineEvent(event){
    if (event.type == "offline") {
      // do something here when app is offline
    }
  }

You can check the implementation here See the demo here, open the page, disconnect the wifi or any connected network on your computer.

Upvotes: 1

Related Questions