首页 > 解决方案 > 如何检查互联网连接并使用本地存储数据

问题描述

在我的 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();
        })


  }

标签: angulartypescriptionic-framework

解决方案


要在 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();

希望这将有助于获得网络连接/断开状态。

参考链接: https ://ionicframework.com/docs/native/network


推荐阅读