Last active
September 15, 2020 00:53
-
-
Save zimejin/d706928b0858df9b59b6ee605a59ec1e to your computer and use it in GitHub Desktop.
Exit ionic 4 app on pressing back button.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() } | |
}); | |
} |
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
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!