Use a back button of the phone to call a function


#1

Hi, I need to trigger a function when the user touch the back button in the android’s phones, just right now when the user touch the back button the app close.


#2

Can you elaborate a bit more? Are you talking about the back button within the ionic app?

For example, when using nav.push()? Or are you navigating outside of the app?


#3

Thanks Raytri, I refer to the back button in the hardware of the mobile


#4

Gotcha. So what you’re going to want to do is hook into the platform through your app.component.ts

           platform.ready().then(() => {
              // Make sure platform is ready first

              platform.registerBackButtonAction(() => {
                //do something
              });
            });

More information can be found here:


#5

Thanks!! This is that I want, just a another “little” question, how I can in the “Do something” modify var of a view, for example, pass a var of false to true in the home?

 platform.registerBackButtonAction(() => {
                //do something <----
              });

#6

Hm. For any variables that ‘change’ across pages I typically use providers.

app.component.ts

import someProvider from {../providers/something/someProvider.ts};
....
 platform.registerBackButtonAction(() => {
               this.someProvider.setVar(var);
 });

home.component.ts

ionViewDidLoad(){
      this.var = this.someProvider.var;
}

For more information on providers, Josh Morony gives us a pretty good intro here: https://www.joshmorony.com/an-in-depth-explanation-of-providers-in-ionic-2/


#7

Thanks so much!
I can use it just importing platform in every view in the .ts and put the
platform.registerBackButtonAction(() => { //do something <---- });
inside the construtor and work!!!