如果有网络连接,但如果互联网不工作. 示例 有一个 wifi 连接,但 wifi 没有互联网连接,浏览器可观察的应该触发"加载错误"事件。
法典:
import { Component } from '@angular/core';
import { Platform,AlertController,LoadingController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { Network } from '@ionic-native/network';
import { HomePage } from '../pages/home/home';
import { InAppBrowser } from '@ionic-native/in-app-browser';
@Component({
templateUrl: 'app.html'
})
export class MyApp {
public rootPage:any = HomePage;
constructor(private platform: Platform,private statusBar: StatusBar,private splashScreen: SplashScreen, private network: Network, private alertCtrl: AlertController, private iab: InAppBrowser, private loadingCtrl: LoadingController) {
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.
let alert = this.alertCtrl.create({
title: "Network Problem",
subTitle: 'Internet is not connected' ,
buttons: [
{
text: 'Close', handler: () => {
this.platform.exitApp();
}
}
]
});
const loading = this.loadingCtrl.create();
if(this.network.type !== 'none') {
loading.present();
const browser = this.iab.create('http://www.google.com','_blank','location=no,clearsessioncache=yes');
browser.on("loaderror").subscribe(() => {
loading.dismiss();
this.iab.create('http://192.168.2.222/users/dashboard','_blank','location=no,clearsesioncache=yes');
});
const sub = browser.on('loadstart').subscribe(() => {
loading.dismiss();
sub.unsubscribe();
},
err => { loading.dismiss(); console.log('error') ; alert.present()},
() => { loading.dismiss(); console.log('success') });
}
/// check connectivity automatically .
let connectSubscription = network.onConnect().subscribe(() => {
loading.present();
const browser = this.iab.create('http://www.google.com','_blank','location=no,clearsesioncache=yes');
browser.on("loaderror").subscribe(() => {
loading.dismiss();
this.iab.create('http://192.168.2.222/users/dashboard','_blank','location=no,clearsesioncache=yes');
});
});
let disconnectSubscription = network.onDisconnect().subscribe(() => {
const browser = this.iab.create("error.html",'_blank','location=no');
});
statusBar.styleDefault();
splashScreen.hide();
});
}
}
但它总是加载谷歌页面,即使在清除会话缓存和互联网断开连接之后,它总是被加载。我在安卓和桌面上都对此进行了测试。
您可以尝试如下所示。
注意:因此,您必须使用如下所示loader
,它具有一定的延迟。
goToWebPage() {
const loading = this.loadingCtrl.create();//use loader
loading.present();
const browser = this.iab.create('http://www.google.com');
const sub = browser.on('loadstart').subscribe(() => {
loading.dismiss();
sub.unsubscribe();
},
err => { loading.dismiss();console.log('error'); },
() => { loading.dismiss();console.log('success') });
}