在我的提供程序中,我进行了所有API调用,它们看起来像这样:
listSavedJobs() : Promise <any> {
let headers = new Headers({ 'Authorization': localStorage.getItem('token') });
return this.http.get(this.savedJobs, { headers:headers })
.map(res => res.json())
.map(resJson => resJson)
.toPromise().catch(function(error) {
console.log (error)
});
}
我编写了一个脚本来检测网络中的变化
networkConnection(){
try{
console.log ('called network')
this.network.onConnect().subscribe(data => {
console.log( data)
}, error => console.error(error));
this.network.onDisconnect().subscribe(data => {
console.log( data)
this.networkStatus()
}, error => console.error(error));
} catch(e){
console.log ('network error' + JSON.stringify(e))
}
}
networkStatus(){
let alert = this.alertCtrl.create({
title: 'Network Error ',
message: 'No internet connectivity detected. Please try again.',
});
alert.present();
}
但是当我尝试在catch中调用networkConnection函数时,它会抛出未定义的错误。我该如何解决这个问题?
答案 0 :(得分:0)
Netowrk检测应该是自动的。您只需在启动应用时订阅onConnect
或onDisconnect
即可。以下是处理网络连接并根据连接可用性进行订阅的工作代码。
如果互联网恢复,它会自动隐藏消息。
network.provider.ts
import { Injectable } from '@angular/core';
import { Network } from '@ionic-native/network';
import { Platform, IonicApp } from 'ionic-angular';
import { SharedProvider } from '../providers/shared.provider';
declare var Connection;
@Injectable()
export class NetworkProvider {
onDevice: boolean;
toastAlert: any;
constructor(private _shared: SharedProvider, public platform: Platform, public ionicApp: IonicApp, private network: Network) {
this.onDevice = this.platform.is('cordova');
}
startWatchingConnection() {
this.network.onDisconnect().subscribe(() => {
let activePortal = this.ionicApp._toastPortal.getActive();
if (!activePortal) {
this.alertOffline();
}
});
this.network.onConnect().subscribe(() => {
let activePortal = this.ionicApp._toastPortal.getActive();
if (activePortal) {
activePortal.dismiss();
}
});
}
alertOffline() {
this._shared.Toast.show('No Connection', null, 'bottom', true, 'Ok');
}
isOnline(): boolean {
console.log( this.network.type);
if (this.onDevice && this.network.type) {
return this.network.type !== Connection.NONE;
} else {
return navigator.onLine;
}
}
}
<强> app.component.ts 强>
import { NetworkProvider } from '../providers/network.provider';
constructor(platform: Platform, public network: NetworkProvider) {
platform.ready().then(() => {
if (network.isOnline()) {
network.startWatchingConnection();
} else {
network.alertOffline();
network.startWatchingConnection();
}
});
}
this._shared.Toast.show('No Connection', null, 'bottom', true, 'Ok')
来电 -
public Toast = {
show: (text: string, duration?, position?, closeButton?, btnText?) => {
this._toastMsg = this._toastCtrl.create({
message: text,
duration: duration || closeButton ? null : 3000,
position: position || 'top',
showCloseButton: closeButton || false,
closeButtonText: btnText || 'OK'
});
this._toastMsg.present();
},
hide() {
this._toastMsg.dismiss();
}
}