How to load a plugin when starting the application (Network Plugin)


#1

Hello, I have a problem with this plugin. I wish that by running the application I know if I am connected or not. apprament the plugin works when there is change of state


#2

What plugin? Could you provide a link?


#3

#4

@arsene123

I am able to detect if my apps are booted in an offline state by first waiting if the platform is ready (using the platform plugin https://ionicframework.com/docs/api/platform/Platform/), and then creating subscriptions for the connect and disconnect events. Due to quirks documented in the GitHub readme for the Network Plugin you should wait at least one second (from creating the subscriptions) before determining an offline/online status.


#5

can you make an example with an http query? if the mobile is connected start the request


#6

A minimal service would look like the following (mainly borrowed from the plugin’s documentation):

@Injectable()
export class NetworkCheckService {
   constructor(private network:Network){}

   // called from a platform.ready() subscription:
  public init(){
    this.network.onDisconnect().subscribe((r) => {
      setTimeout(() => {
        this.checkNetwork();
      }, 1000);
    });
   this.network.onConnect().subscribe((r) => {
      // 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(() => {
        this.checkNetwork();
      }, 1000);
    });
    setTimeout(() => {
      this.checkNetwork();
    }, 1000);
  }

  private checkNetwork(){
    console.log(this.network.type);
  }
}

#7

i get null in the console


#8

What is the output if you disconnect/reconnect the network on the device?

You may get null if the plugin isn’t initialized or not enough time has processed as discussed in the quirks on the GitHub readme.


#9

how to detect the state of the network directly?


#10

#11

i want to call this function if only i have internet connection :

this.cardiologueData.load().then((datas)=>{
        this.reponse = datas;
        loading.dismiss();
        console.log(datas);
    }).catch((error)=>{
      loading.dismiss();
      setTimeout(()=>{
        loading.dismiss();
      })
    }) 

#12

Then I would call that function from checkNetwork() IIFF the connection type is not NONE.


#13

something like :

if(this.network.type==="3g"){
      this.loadData();
    }
    else if(this.network.type==="none"){
      alert("offline");
    }

#14

That would work assuming the strings indeed match “3g” and “none” when your app is detecting an online and offline state.


#15

so I can work this way does not it matter?


#16

Given those assumptions, it does not matter.


#17

your opinion is important, is a good way to do it?


#19

It depends on the application.


#20

I do a query to my API to display a list of doctor, and I will like to do it as other app