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

@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 …

2 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

1 Like

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