Ionic 4 network check example problem

Im confused when i want to make a ionic network plugin to check for connection all the time when user uses an app. I’ve tried an example from ionic website but without any results.

import { Network } from '@ionic-native/network/ngx'; //ngx

constructor(private network: Network) { }

...

// watch network for a disconnect
let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
  console.log('network was disconnected :-(');
});

// stop disconnect watch
disconnectSubscription.unsubscribe();


// watch network for a connection
let connectSubscription = this.network.onConnect().subscribe(() => {
  console.log('network connected!');
  // We just got a connection but we need to wait briefly
   // before we determine the connection type. Might need to wait.
  // prior to doing any api requests as well.
  setTimeout(() => {
    if (this.network.type === 'wifi') {
      console.log('we got a wifi connection, woohoo!');
    }
  }, 3000);
});

// stop connect watch
connectSubscription.unsubscribe();

Anyone say that i need to add it in app.component.ts but still doesnt work. Somebody can help ? THanks

1 Like

@klejz0r

network.service.ts

import { Injectable } from '@angular/core';
import { Network } from '@ionic-native/network/ngx';
import { Platform } from '@ionic/angular';
import { fromEvent, merge, of, Observable } from 'rxjs';
import { mapTo } from 'rxjs/operators';

@Injectable()
export class NetworkService {
    private online$: Observable<boolean> = undefined;

    constructor(public network: Network, public platform: Platform) {
        this.online$ = Observable.create(observer => {
            observer.next(true);
        }).pipe(mapTo(true));

        if (this.platform.is('cordova')) {
            // on Device
            this.online$ = merge(
                this.network.onConnect().pipe(mapTo(true)),
                this.network.onDisconnect().pipe(mapTo(false))
            );
        } else {
            // on Browser
            this.online$ = merge(
                of(navigator.onLine),
                fromEvent(window, 'online').pipe(mapTo(true)),
                fromEvent(window, 'offline').pipe(mapTo(false))
            );
        }
    }

    public getNetworkType(): string {
        return this.network.type;
    }

    public getNetworkStatus(): Observable<boolean> {
        return this.online$;
    }
}

home.module.ts

...
import { NetworkService } from '../services/network.service';

@NgModule({
...
providers: [NetworkService]
})

home.page.ts

...
// Services
import { NetworkService } from '../services/network.service';

    constructor(
        ...
        public networkService: NetworkService,
    ) {}

    ngOnInit(): void {
        console.log('[Home] OnInit');
        this.networkSubscriber();
    }

    networkSubscriber(): void {
        this.networkService
            .getNetworkStatus()
            .pipe(debounceTime(300))
            .subscribe((connected: boolean) => {
                this.isConnected = connected;
                console.log('[Home] isConnected', this.isConnected);
                this.handleNotConnected(connected);
            });
    }

Hope that helps you …

6 Likes

Yes it gives “true” while network is connected but did not detecting when network is gone ?
how can I do that… ?
in this case I need to import it all pages of the app, is it possible that I can put the app.component.ts and it is available on whole project ?

@Thesurya9

I’ve tested on Chrome @ iMac and it really fails detecting offline …
I also removed internet cable to be sure there was no internet.
Nothing triggered.
On Devices it works well.
Have searched some info and only i got was this:

And yes to have in all App, do it in App.component :wink:

1 Like

How did you get the offline connection? Share me pls . I have problem too.

use this plugin
1- https://ionicframework.com/docs/native/network

2- then in your app.compounent.ts

  this.disconnectSubscription = this.network.onDisconnect().subscribe(() => {
      this.presentAlert(); //some alert msg that netwk has gone 
    });

    this.connectSubscription = this.network.onConnect().subscribe(() => {
      this.toast
        .show("Network connected!", "2000", "bottom")
        .subscribe(toast => {});
    });

that’s it .
and this will on device only. write that code in constructor only

2 Likes

No need to add login page?. I still can’t achieve it even i added it on app.component.ts.
First, I tested on app.component.ts and run it on emulator. it didn’t work.
And I tried to add those code on login page as well. it didn’t show the message too. Sad.

show me your code .
you dont need to create app.component.ts…
if it is ionic 4 app then it must be present there.

1 Like

Hello Bro, I have another problem with photo selection and deletion before i upload. Here is my issue . I was finding it and still stuck on it. Could you please help me? Thank you so much

Works great, but how do you unsubscribe from the networkSubscriber?

Hi I’m getting an error like this;

Why it may have caused this error? Can you help me?

Have you declared “disconnectSubscription” property

Error when declared.

edit: it’s okay. but when i open the application comes the success message. is there any way to prevent it?

Yes, this is BehaviourSubject and it provides (emits) initial value. You could use ReplaySubject or Subject itself.

How can I do it? (20 characters!)

You may be interested in this post, which covers basically the same topic.

Hi all guys, don’t use plugins for network checking, I got an very very and very easy way to check if the user has internet connection or not, so all we have to do is that to use this:

if (navigator.onLine) {
   console.log('Internet is connected');
} else {
   console.log('No internet connection');
}

at here navigator is not a variable created by me. The navigator . onLine property provides a boolean value whether or not the user is connected to the internet. … Browser and real device also supports online and offline events whenever the browser is goes offline or comes online .
this is the very easy and working way, I’m sure it will help.

4 Likes

navigator.onLine works really well on browsers but isn’t that much of a use when on mobile devices. It always remains true and does not change to false even if the device is disconnected from the network.

2 Likes

i have this code for network detection working good in 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();
  }
}

it detects accurately when the device is offline and not. i tried it with the airplane mode it works good hope it helps some one :slight_smile:

7 Likes

Hello, you said that your code, works perfectly, you tried to disconnect the cable that provide connection to the wifi, in this model I realized that the answer remains true