如何在离线查看Ionic 3应用程序时显示Firebase数据库连接错误警报

时间:2018-02-06 14:02:37

标签: typescript firebase ionic-framework firebase-realtime-database

美好的一天,

我正在研究Ionic 3应用程序,为了获得良好的用户体验,我想展示一个警报控制器弹出窗口,要求用户确保他们在离线时在线连接,也许例如,在iPhone上的“飞行模式”下打开应用程序。

这是我当前的代码无效:

  

about.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import firebase from 'firebase';
import { LoadingController } from 'ionic-angular';
import { AlertController } from 'ionic-angular';

@IonicPage()
@Component({
  selector: 'page-about',
  templateUrl: 'about.html',
})
export class AboutPage {

  info = [];

  constructor(public navCtrl: NavController, public navParams: NavParams, 
    public loadingCtrl: LoadingController, private alertCtrl: AlertController) {

    let loader = this.loadingCtrl.create({
      content: "Loading Data",
      spinner: 'dots'
      });
      loader.present();

    firebase.database().ref('about').on('value', snapshot => {
      if (this.info = snapshot.val()) {
        loader.dismiss();
      } else {
        loader.dismiss();
        let alert = this.alertCtrl.create({
          title: 'Connection Failed!',
          message: 'Please make sure you are connected online and try again.',
          buttons: ['Ok']
          });
        alert.present();
      }

  });

  }

}

使用上面的代码,加载微调器工作正常,并在加载内容时被解除,但是,如果我离线运行应用程序,则警报永远不会显示。谢谢。

2 个答案:

答案 0 :(得分:2)

如果应用未连接到互联网,则Firebase客户端无法知道firebase.database().ref('about')是否有值,因此它不会触发任何值事件。这是预期的行为。

幸运的是Firebase内置支持这个用例。如果您收听.info/connected,则触发一个布尔值,指示该设备是否已连接到Firebase服务器。

来自documentation on detecting connection state

var connectedRef = firebase.database().ref(".info/connected");
connectedRef.on("value", function(snap) {
  if (snap.val() === true) {
    alert("connected");
  } else {
    alert("not connected");
  }
});

答案 1 :(得分:0)

如果您想在连接丢失后立即显示提醒,请使用this原生插件

在根组件中

    let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
  console.log('network was disconnected :-(');
//display your alert here
        });