I have integrated a provider in my app that needs to stay active at all times while the application is running to monitor the network connection status.
Following this guide, I included the class in my app.module.ts
file to ensure it functions as a global instance. As per my understanding, the service should be operational when the app initializes its root component (in this case, app.module.ts
).
Issue: The provider does not get called until a specific page within the app imports and utilizes it.
In the tutorial mentioned, the provider
is imported like so:
ionicBootstrap(MyApp, [TestProvider]);
However, this approach did not work for me. According to this response, the guide might be outdated.
Query: How can I utilize providers
in Ionic 3
to ensure they are accessible as a single instance after launching the application?
Snippet from my app.module.ts:
import { NetworkConnectionProvider } from '../providers/networkconnection/networkconnection';
// (...)
@NgModule({
declarations: [
MyApp,
// (...)
],
imports: [
BrowserModule,
HttpModule,
IonicModule.forRoot(MyApp),
ionicGalleryModal.GalleryModalModule,
],
bootstrap: [
IonicApp
],
entryComponents: [
MyApp,
// (...)
],
providers: [
// (...)
NetworkConnectionProvider
]
})
export class AppModule {}
Code from my provider file:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Network } from '@ionic-native/network';
@Injectable()
export class NetworkConnectionProvider {
private TAG = "NetworkConnectionProvider ";
private isConnectedToInternet: Boolean;
constructor(
public http: Http,
public network: Network
) {
this.isConnectedToInternet = true;
let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
console.log(this.TAG + 'network was disconnected.');
this.isConnectedToInternet = false;
});
// watch network for a connection
let connectSubscription = this.network.onConnect().subscribe(() => {
console.log('network connected!');
this.isConnectedToInternet = true;
// 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(this.TAG + 'wifi connection available');
}
}, 3000);
});
console.log('Hello NetworkConnectionProvider');
}
public subscribeOnConnect() {
return this.network.onConnect();
}
public isConnected(): Boolean{
return this.isConnectedToInternet;
}
public getConnectionType(): string {
return this.network.type;
}
}