TC Roberts
TC Roberts

Reputation: 185

How to show Firebase database connection error alert when viewing Ionic 3 app offline

Good day,

I'm working on an Ionic 3 app and for the sake of a good User Experience I would like to show an Alert Controller pop-up that asks the user to make sure that they are connected online when they are offline, perhaps you open the app whilst in 'Flight Mode' on an iPhone for example.

Here is my current code that is not working:

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

  });

  }

}

With the code above the loading spinner works well, and is dismissed when the content is loaded, however, if I run the app offline, the alert never shows up. Thanks.

Upvotes: 0

Views: 915

Answers (2)

Imdad Ali
Imdad Ali

Reputation: 737

if you want to show alert right after connection lost, Use this native plugin

In your root component

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

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 599111

If the app isn't connected to the internet, the Firebase client doesn't know if there is a value at firebase.database().ref('about') so it doesn't fire any value event. That is the expected behavior.

Luckily Firebase has built-in support for precisely this use-case. If you listen to .info/connected, it will fire a boolean value that indicates whether the device is connected to the Firebase servers.

From the 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");
  }
});

Upvotes: 2

Related Questions