Dismissing loader after timeout, if no database connection available

In my Ionic 2 mobile app, I use AngulaFire2 to receive data from Firebase.

Typically, I add a LoadingController while the data is fetched from Firebase to show the user that the system is still working. The loader is dismissed, as soon as the data is received successfully, or an error occured. However, if the user is not connected to the Internet, the loader will never stop showing - continuing forever, since no data is fetched and no error occures.

I would like to add a timeout, that stops the loader after a couple of seconds and shows an alert ā€œno connectionā€. Then the user is able to continue using the app with the data that is already loaded to localstorage.

Any idea how to implement this is appreciated. This is an example code:

ionViewDidLoad() {

   let loader = this.loadingCtrl.create({
      content: "Getting data..."
   });

   loader.present().then(() => {

      // get all products
      this.productService.getAllProductsOnce().subscribe(data => {
        this.allProducts = data;
        loader.dismiss();

      }), error => { 
        loader.dismiss();
        this.errorService.handleError(error);
      };
   }
}

Found help on Stackoverflow:

1 Like

Another option is the duration property of the config passed to LoadingController.create().

@rapropos: Thanks for the suggestion. I like the idea of solving this by just adding a parameter. Feels cleaner than a timeout. How would you manage to show an alert or anything similar to the user saying ā€œno internetā€, as soon as the loader is dismissed?

First thing I would try is giving it an onDidDismiss() handler, but you would have to make that handler able to figure out whether it was happily dismissed or not, which might end up being as if not more complicated than your timeout on the network request.

Alright. I might give this a try for the functions I subscribe to, permanently. When I have an active observer, I canā€™t use the timeout, since the observer will be active all the time and, hence, always fire the timeout-error.

Thank you!