Disable android hardware back button while loading

Hello there,
I created a loader with the LoadingController.

import { Injectable } from '@angular/core';
import { LoadingController } from 'ionic-angular';
import { Platform } from 'ionic-angular';

@Injectable()
export class Loader {
  loader: any;
  isLoading: boolean;

  constructor(public loadingCtrl: LoadingController, public platform: Platform) {
    this.isLoading=false;
  }

  startLoading(msg, dismissOnPageChange=true){
    if(this.isLoading){
      this.loader.data.content = msg;
      return;
    }
    this.loader = this.loadingCtrl.create({
      content: msg,
      dismissOnPageChange :dismissOnPageChange 
    });
    this.loader.present(); 
    this.isLoading=true;
  }

  stopLoading(){
    this.loader.dismiss();
    this.isLoading=false;
  }

}

It prevents the user from leaving a page, as long, as the user doesnt use its hardware back button.
Is there any way, to “disable” the hardware button when StartLoading is called and “enable” it, when stopLoading is called?

Thanks for any help.

Skee

1 Like

1 year later, still doesn’t know a proper way to do that

I haven’t tested it but you could try to use Nav Guards for that.

ionViewCanLeave() {
  return !this.isLoading;
}
1 Like

Yes, thats how i solved it.
On every page, where a loading action takes place, i include the loading provider.
And when the user wants to leave a page i use the navguard, to check if the user is within a loading process. And if he is, i decline the page switch.
Works quite good.

1 Like

Hi, I developed a solution for this.
I did it by wrapping the LoadingController.

import {Injectable} from "@angular/core";
import {Loading, LoadingController, LoadingOptions, Platform} from "ionic-angular";


@Injectable()
export class LoaderController {

  constructor(
    private loadingCtrl: LoadingController,
    private platform: Platform
  ) {

  }

  create(opts?: LoadingOptions): Loading {
    let subscription;
    let loading = this.loadingCtrl.create(opts);

    loading.willEnter.subscribe(() => {
      subscription = this.platform.registerBackButtonAction(() => {
        console.log('back button pressed');
      }, 10);
    });

    loading.onDidDismiss(() => {
      subscription();
    });

    return loading;
  }
}

Every Loading you create will replace the backButton original behaviour.

Just make sure in your project there is no backButton action with a higher priority (in this case, I set it to 10).

1 Like