我有一个提供程序,当应用程序运行时,必须始终启动以监视网络连接状态.
所以根据tutorial我已经将类添加到我的app.module.ts文件中,使其成为一个全局实例.所以据我所知,当应用初始化它的根组件(因此app.module.ts)时,服务应该启动.
问题:在应用程序的特定页面导入并使用它之前,不会调用提供程序.
在上面提到的教程中,提供者是这样导入的:
ionicBootstrap(MyApp,[TestProvider]);
不幸的是,这对我不起作用. post说这个全新的教程已经过时了.
问题:如何在启动应用程序后将Ionic 3中的提供程序用作一个实例?
我的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 {}
我的提供者:
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; } }
解决方法
要实现这一点,应用程序在启动时创建提供程序的实例(对于监视网络状态的网络提供程序有意义),只需将提供程序添加到app.module.ts
providers: [ NetworkConnectionProvider ]
之后,将其添加到app.component.ts的构造函数中
constructor( platform: Platform,statusBar: StatusBar,splashScreen: SplashScreen,private sideMenuService: SideMenuService,network: NetworkConnectionProvider ) { platform.ready().then(() => { // Okay,so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. statusBar.styleDefault(); splashScreen.hide(); }); // other stuff }
每次导入提供程序并稍后在应用程序中使用它时,它将是同一个实例.