0

I need help with ionic Network plugin. Here's a code, but it doesn't work for me. No console log or any other modals. No errors. at the top

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

ionViewDidLoad() {
    this.getWarrentsNumber();
    let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
        console.log('network was disconnected :-(');
    });

    disconnectSubscription.unsubscribe();

    let connectSubscription = this.network.onConnect().subscribe(() => {
        console.log('network connected!');
        setTimeout(() => {
            if (this.network.type === 'wifi') {
                console.log('we got a wifi connection, woohoo!');
            }
        }, 3000);
    });

    connectSubscription.unsubscribe();
}
Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56
  • Remove both `unsubscribe()` and try again please. We will fix this if this solve the problem. – Jacopo Sciampi Feb 27 '19 at 08:05
  • @JacopoSciampi i've just commented both two lines // disconnectSubscription.unsubscribe(); and // connectSubscription.unsubscribe(); but it still doesnt work. –  Feb 27 '19 at 08:12
  • Ok, thanks. For now, leave them commented. Who call the function `ionViewDidLoad()` ? – Jacopo Sciampi Feb 27 '19 at 08:14
  • ionViewDidload() is the function from ionic app. It means it will open any functions in them while app is opened. I also tried to create a function left from ionviewdidload but still happens without any progress. –  Feb 27 '19 at 08:16
  • It could maybe be a dumb question, but are you sure that this function is called? Have you tried putting a breakpoint at `this.getWarrentsNumber();` to see if the code is reached? – Jacopo Sciampi Feb 27 '19 at 08:19
  • Are you sure you get a connection? You have to connect to network after your app opens. If you are already connected to WiFi I don't believe onConnect will emit anything – Arif Feb 27 '19 at 08:29
  • But that is the point i mean @Arif . Im testing an app from chrome browser, and app need automatically to scan is there connection or not. –  Feb 27 '19 at 08:31
  • @JacopoSciampi i've commented that line, and everything is the same. When user log in to an app, on HomePage, i need to scan is there connection or not. –  Feb 27 '19 at 08:33
  • I'll investigate. – Jacopo Sciampi Feb 27 '19 at 08:37

3 Answers3

0

Declare your variables connectSubscription & disconnectSubscription as class properties and then try to unsubscribe() them in ioniViewWillLeave() hook instead of ionViewDidLoad(). So the code would look similar to the following -

connectSubscription: any;
disconnectSubscription: any;

ionViewDidLoad() {
    this.getWarrentsNumber();
    this.disconnectSubscription = this.network.onDisconnect().subscribe(() => {
        console.log('network was disconnected :-(');
    });

    this.connectSubscription = this.network.onConnect().subscribe(() => {
        console.log('network connected!');
        setTimeout(() => {
            if (this.network.type === 'wifi') {
                console.log('we got a wifi connection, woohoo!');
            }
        }, 3000);
    });
}

ioniViewWillLeave() {
    this.disconnectSubscription.unsubscribe();
    this.connectSubscription.unsubscribe();
}
Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56
0

That code works properly but it works dependent platform like android or ios. It may not console anything on the browser I think. Please test your application with respect to the platform device.

or else you can use ngOnInit() instead of ionViewDidLoad();

mepraveenk
  • 226
  • 1
  • 11
  • cant user ngOnInit() instead of ionVIewDidLoad(); because its not an angular app..Its ionic app. –  Feb 27 '19 at 10:10
  • you can use ngOnInit() but the thing is you have to implement the class with OnInit. can you look into this https://stackoverflow.com/questions/43703271/ngoninit-vs-ionviewdidload-in-ionic-2 I check your code with ngOnInit() on my application it is working. – mepraveenk Feb 27 '19 at 11:03
  • Please import the OnInit before you using and Implement the class with OnInit // import { Component, OnInit } from '@angular/core'; export class YourClassName implements OnInit { } – mepraveenk Feb 27 '19 at 12:22
0

Here is the quote from plugin's official github repo

The online event fires when a previously unconnected device receives a network connection to allow an application access to the Internet. It relies on the same information as the Connection API, and fires when the connection.type changes from NONE to any other value.

As you can see onConnect will only emit something when previously unconnected device receives a network connection.

To check on startup if device is online you can directly check this.network.type

Or

You can create a service which will handle all these

@Injectable()
export class MyNetworkService implements OnInit {
  public connection: BehaviorSubject<string> = new BehaviorSubject(null);
  constructor(private network: Network, private platform: Platform) {

    this.connection = this.network.type;
    this.platform.ready().then(() => {
      this.network.onConnect().subscribe(() => {
        this.connection = 'something';
      });
      this.network.onDisconnect().subscribe(() => {
        this.connection = 'none';
      });
    });
  }

  ngOnInit() {
    this._setCurrentConnectionType();

    this.platform.ready().then(() => {
      this.network.onConnect().pipe(timer(3000)).subscribe(this._onConnectHandler);
      this.network.onDisconnect().pipe(timer(3000)).subscribe(this._onDisconnectHandler);
    });
  }

  private _onConnectHandler= () => this.connection.next(this.network.type);

  private _onDisconnectHandler = () => this.connection.next('offline');
}

And then you can inject your service where-ever you want and subscribe to connection.

constructor(private myNetworkService: MyNetworkService) {
  this.myNetworkService.connection.subscribe(type => {
    // you might filter out nulls
    // Before subscribe add .pipe(filter(type => type !== null))
  })

}
Arif
  • 1,617
  • 9
  • 18
  • I need to check for connection not only on startup, i need it in few pages....also when user get a connection he will see a toast msg that connection is OK or NOT. THats the point. –  Feb 27 '19 at 13:42
  • With behaviour subject you can even do myNetworkService.connection.getValue() or subscribe where-ever you want. It doesn't matter if it is a startup or some nested component – Arif Feb 27 '19 at 13:45