Skip to content

Instantly share code, notes, and snippets.

@zimejin
Last active September 15, 2020 00:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zimejin/d706928b0858df9b59b6ee605a59ec1e to your computer and use it in GitHub Desktop.
Save zimejin/d706928b0858df9b59b6ee605a59ec1e to your computer and use it in GitHub Desktop.
Exit ionic 4 app on pressing back button.
import { fromEvent } from "rxjs"; // import fromEvent from rxjs
import { Router } from "@angular/router"; // import angular router as well
import { Location } from "@angular/common"; // import location from angular common,
// Inject Router and Location
constructor(private router: Router, private location: Location,) {
// Call the funtion when the app initializes at app.component.ts. it will watch for backbutton events globally in
// the application
this.backButtonEvent();
}
// Function to present the exit alert
async exitAlert() {
const alert = await this.alertController.create({
// header: 'Confirm!',
message: "Are you sure you want to exit the app?",
buttons: [
{
text: "Cancel",
role: "cancel",
cssClass: "secondary",
handler: blah => {}
},
{
text: "Close App",
handler: () => {
navigator["app"].exitApp();
}
}
]
});
await alert.present();
}
// write function to subscribe to the backbutton event
backButtonEvent(): void {
const event = fromEvent(document, "backbutton");
event.subscribe(async () => {
// When the current route matches a specific page in the app where u want this function to work.
// else it assumes the user wants to navigate to a previous page
if(this.router.url === "<example page-url to exit from>") { this.exitAlert() }
else { this.location.back() }
});
}
@EbenOladutemu
Copy link

I found this extremely useful. Shocked not to see any comments or stars and many devs have this problem with exiting ionic apps. Thanks a whole lot!

@zimejin
Copy link
Author

zimejin commented Sep 15, 2020

I found this extremely useful. Shocked not to see any comments or stars and many devs have this problem with exiting ionic apps. Thanks a whole lot!

Thank you, I'm really glad it was useful to you :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment