如果互联网在我的应用的任何位置关闭,我正在寻找更好的连接失败弹出对话框解决方案。
我有提供商检查连接。但是我没有得到很好的解决方案来调用每个事件或每次更改页面。
答案 0 :(得分:9)
你可以订阅一个活动。
我建议你做以下事情;
AppComponent.ts
export class MyApp {
constructor (
private network: Network,
private platform: Platform,
private alertCtrl: AlertController,
) {
platform.ready().then(() => {
this.listenConnection();
})
}
private listenConnection(): void {
this.network.onDisconnect()
.subscribe(() => {
this.showAlert();
});
}
private showAlert(): void {
// omitted;
}
}
这样,您就可以在所有应用程序中监听断开连接事件。 当然,您可以在提供程序中隔离此代码,并在用户登录或其他一些业务规则后进行调用。
我希望它可以帮到你。
答案 1 :(得分:2)
没有针对此问题的完整证明解决方案。仅当应用程序运行时网络状态发生变化时,它才有效。如果在断开网络连接的情况下启动应用程序,该怎么办。不会更改this.disconnec
的值答案 2 :(得分:0)
在app.component.ts上执行此操作:
import { Network } from '@ionic-native/network';
...
export class MyApp {
disconnect: boolean;
...
constructor(Network: Network,ngZone: NgZone,...){
Network.onDisconnect().subscribe(() => {
// You can do everything you want here on disconnected situation.
// for example using NgZone.run() for executing work inside or
//outside of the Angular zone to optimize performance
ngZone.run(() => { this.disconnect = true; });
});
Network.onConnect().subscribe(() => {
// You can do everything you want here on connected situation.
ngZone.run(() => { this.disconnect = false; });
});
}
}
答案 3 :(得分:0)
我遵循@HamidAraghi示例,并将其添加到ngOnit导航器中.Angular提供的OnLine可以在启动应用程序时设置networkStatus布尔值...希望有帮助
networkStatus:boolean;
connectSubscription$: Subscription = null;
disconnectSubscription$: Subscription = null;
constructor(
public navctrl: NavController,
private afdb: AngularFireDatabase,
public plt: Platform,
public afAuth: AngularFireAuth,
public route: Router,
private alertCtrl: AlertController,
private networkService: NetworkStateService,
private network: Network,
public ngZone: NgZone
) {
// check internet connection
// watch network for a disconnection
this.disconnectSubscription$ = this.network.onDisconnect().subscribe(() => {
this.ngZone.run(() => {
this.networkStatus = false;
});
this.networkService.presentToast(`You're offline! ? `);
});
// watch network for a connection
this.connectSubscription$ = this.network.onConnect().subscribe(() => {
this.networkService.presentToast(`You're online! ? `);
this.ngZone.run(() => {
setTimeout(() => {
if (this.network.type !== "none") {
this.networkService.presentToast(
`You got! ? ${this.network.type}`
);
this.networkStatus = true;
}
}, 1500);
});
});
}
ngOnInit() {
// if we have internet connections
if (navigator.onLine) {
this.networkStatus = true;
this.getAlarm();
} else {
this.networkStatus = false ;
}
}