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
What plugin? Could you provide a link?
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.
can you make an example with an http query? if the mobile is connected start the request
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);
}
}
i get null in the console
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.
how to detect the state of the network directly?
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();
})
})
Then I would call that function from checkNetwork()
IIFF the connection type is not NONE.
something like :
if(this.network.type==="3g"){
this.loadData();
}
else if(this.network.type==="none"){
alert("offline");
}
That would work assuming the strings indeed match “3g” and “none” when your app is detecting an online and offline state.
so I can work this way does not it matter?
Given those assumptions, it does not matter.
your opinion is important, is a good way to do it?
It depends on the application.
I do a query to my API to display a list of doctor, and I will like to do it as other app