I had to do the subscription in the constructor method for the app to detect the subscription properly.
But since I had to enable the back button for child views and only disable the back button on the top parent view, I had to set a local boolean value according to whether I was in the parent view or not.
Here’s the solution that I did to make it work (in case somebody else might stumble upon this challenge):
private isCurrentView: boolean;
private displayWarning: boolean;
constructor(private platform: Platform) {
this.subscriptions.add(
this.platform.backButton.subscribeWithPriority(9999, (processNextHandler) => {
if (this.isCurrentView) {
this.displayWarning = true;
// Or other stuff that you want to do to warn the user.
} else {
processNextHandler();
}
})
}
ionViewDidEnter() {
this.isCurrentView = true;
}
ionViewWillLeave() {
this.isCurrentView = false;
}
I only execute the processNextHandler() if I am not in the parent view - this enables the native back button function.
I hope this would be helpful to others.