I have a provider that has to be always up when the app is running to watch for the network connection status.
So according to that tutorial I have added the class to my app.module.ts file to make it a global instance. So as far as I understand it, the service should be up when the app initializes it's root component (thus app.module.ts).
Problem: The provider gets not called until a specific page of the app imports and uses it.
In the mentioned tutorial the provider is imported like that:
ionicBootstrap(MyApp, [TestProvider]);
Unfortunately that does not work for me. That post says that this quite new tutorial is outdated.
Question: How could I use providers in Ionic 3 that they are available as one instance after launching the application?
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 {}
My provider:
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;
}
}