gpt4 book ai didi

angular - Ionic 3 中提供者的全局实例

转载 作者:太空狗 更新时间:2023-10-29 17:49:48 25 4
gpt4 key购买 nike

我有一个提供程序,它必须在应用程序运行时始终处于运行状态以监视网络连接状态。

所以根据tutorial我已将该类添加到我的 app.module.ts 文件中,使其成为一个全局实例。据我所知,当应用程序初始化它的根组件时,服务应该启动(因此 app.module.ts)。

问题:在应用程序的特定页面导入并使用它之前,不会调用提供程序。

在提到的教程中,provider 是这样导入的:

ionicBootstrap(MyApp, [TestProvider]);

不幸的是,这对我不起作用。那post说这个相当新的教程已经过时了。

问题:我如何在 Ionic 3 中使用 providers,它们在启动后作为一个实例可用应用程序?

我的 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
}

每次在应用程序中导入和使用该提供程序时,它都将是同一个实例。

关于angular - Ionic 3 中提供者的全局实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46422120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com