angular - 如何检查互联网连接并使用本地存储数据
问题描述
在我的 home.ts 文件中,如果 Internet 连接处于离线状态,我想使用 localStorage 项目。这是一个代码。当我在这里添加 IF 时,我遇到了太多错误。如果 Internet 处于离线状态,我想在 '__mydb/_ionickv/DodNalog' 的代码中使用下面的这个 getItem。
getStorageWarents() {
this.storage.ready()
.then(() => {
this.warrentsInStorage = JSON.parse(localStorage.getItem('__mydb/_ionickv/DodNalog'));
console.log("Warrents in storage: ", this.warrentsInStorage);
})
.then(() => {
this.getAssignedWarrents();
})
.then(() => {
this.getAllGoods();
})
.then(() => {
this.getAllCancelTypes();
})
.then(() => {
this.getAllDeviceTypes();
})
.then(() => {
this.getAllManufacturers();
})
.then(() => {
this.getAllIntereventionTypes();
})
}
解决方案
要在 Connect/Disconnect 上获取网络连接更新,您可以在您的应用程序中使用 ionic Network 插件。
Network Plugin
安装:
ionic cordova plugin add cordova-plugin-network-information
npm install @ionic-native/network
如何使用?
import { Network } from '@ionic-native/network/ngx';
constructor(private network: Network) { }
订阅连接/断开连接事件:
let disconnectSub = this.network.onDisconnect().subscribe(() => {
console.log('device network was disconnected');
});
let connectSub = this.network.onConnect().subscribe(() => {
console.log('Device network connected!');
// 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(() => {
console.log('we got a connection, woohoo!');
}, 3000);
});
要停止捕获上述事件,只需取消订阅即可
disconnectSub.unsubscribe();
希望这将有助于获得网络连接/断开状态。
推荐阅读
- c++ - 将 Vulkan 与 SFML 一起使用?
- android - 错误:找不到 exifinterface.jar (com.android.support:exifinterface:27.1.1)
- javascript - 使用 mount() 反应酶,显示来自父级 .html() 的元素,但没有找到带有 .find() 的元素
- scala - 如何使用 Scala 在 Spark 中对 Row 类型的 RDD 进行拆分
- python - 在 qgs Composer 图例中仅显示过滤层 - PyQgis
- jsp - spring boot jsp c:set不使用没有类型的原始值
- java - 先执行服务器调用,然后执行下一行代码
- angular - 如何从角度的SVG图标生成webfont
- node.js - 带有 Puppeteer 的 Headless Chromium 在 Amazon Linux AMI 上不起作用
- python - python 和 windows 文件系统:检查 zip 存档中是否存在文件名