我正在使用Ionic 3,我的问题是应用程序仅在更改后才检查连接。但我需要的是在我的主页加载时检查连接,因为这将触发UI的更改。这就是我所得到的:
constructor(public navCtrl: NavController,private changedetect: ApplicationRef, private weatherProvider: WeatherProvider, private formBuilder: FormBuilder, private network: Network, public alertCtrl: AlertController, private platform: Platform) {
let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
console.log('network was disconnected :-(');
this.netstatus = false;
this.loginbtntxt ="OFLINE";
setTimeout(() => {
// if (this.network.type === 'wifi') {
// console.log('we got a wifi connection, woohoo!');
// }
}, 3000);
});
// watch network for a connection
let connectSubscription = this.network.onConnect().subscribe(() => {
console.log('network connected!');
this.netstatus = true;
this.loginbtntxt ="ONLINE";
// 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('we got a wifi connection, woohoo!');
}
}, 3000);
});
this.login = this.formBuilder.group({
email: ['', Validators.required],
password: [''],
});
}
答案 0 :(得分:0)
万一有人迷失了,我找到了答案:
navigator.onLine
答案 1 :(得分:0)
我有以下提供商,我从各种来源汇总,包括Josh Morony's Tutorials
import { Injectable } from '@angular/core';
import { Platform } from 'ionic-angular';
import { Network } from '@ionic-native/network';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Subscription } from 'rxjs/Subscription';
@Injectable()
export class NetworkConnectivityProvider {
public NetworkStatus: BehaviorSubject<boolean>;
private WatchConnect: Subscription;
private WatchDisconnect: Subscription;
constructor(public platform:Platform, public network: Network) {
console.log('Hello NetworkConnectivityProvider');
this.NetworkStatus = new BehaviorSubject(false); // Assume Network is offline
this.CheckNetworkStatus();
this.CreateNetworkObserverSubscriptions();
}
CheckNetworkStatus() {
if( this.platform.is('cordova') ) {
if( this.network.type === undefined || this.network.type === null || this.network.type === 'unknown') {
this.UpdateNetworkStatus(false);
} else {
this.UpdateNetworkStatus(true);
}
} else {
this.UpdateNetworkStatus(navigator.onLine);
}
}
CreateNetworkObserverSubscriptions() {
this.WatchConnect = this.network.onConnect().subscribe(
data => { this.UpdateNetworkStatus(true); },
error => { console.log(error); }
);
this.WatchDisconnect = this.network.onDisconnect().subscribe(
data => { this.UpdateNetworkStatus(false); },
error => { console.log(error); }
);
}
UpdateNetworkStatus(IsOnline:boolean) {
console.log('Network ', (IsOnline == true ? 'Online' : 'Offline') );
this.NetworkStatus.next(IsOnline);
}
}