问题
On my very initial stage.I am trying to give an ‘Exit the App - Yes/No? ‘ alert when the user presses the hardware back button either from the Login Page or from the home page (after login). The problem I am facing is that the Exit alert message appears on every page when I press the back button and not simply on the Login or home page. Moreover automatically navigating backwards regardless if I press ‘No’ option in the alert box. ] Apologies if have done something wrong I this my first post here. The code I using attaching below-
import { Component, OnInit } from '@angular/core';
import{ Router } from '@angular/router';//
import { AlertController } from '@ionic/angular';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-streams-list',
templateUrl: './streams-list.page.html',
styleUrls: ['./streams-list.page.scss'],
})
export class StreamsListPage implements OnInit {
subscripcion: Subscription;
constructor(
public router:Router,
public alertController: AlertController) {}
ngOnInit() {
this.getBackButtonClick();
}
getBackButtonClick(){
this.subscripcion = this.platform.backButton.subscribe(()=>{
//navigator['app'].exitApp();
this.ClosingApp();
});
}
async ClosingApp()
{
let alert = await this.alertController.create({
header: 'Confirm',
message: 'Message to confirm!!!',
buttons: [{
text: "OK",
handler: () => { this.exit() }
}, {
text: "Cancel",
role: 'cancelar',
}]
})
alert.present();
}
exit()
{
navigator["app"].exitApp();
}
}
回答1:
You can try this approach based on routing. in app.component.ts
constructor(private router: Router){}
Inside your getBackButtonClick()
getBackButtonClick(){
this.subscripcion = this.platform.backButton.subscribe(()=>{
if (this.route.url == '/login' || this.route.url == '/home'){ //please change if your path name is different for login and home
this.ClosingApp();
}
});
}
Further you need to unsubscribe from this
ngOnDestroy() {
this.platform.backButton.unsubscribe();
}
回答2:
You need to unsubscribe from that this.platform.backButton
observable in ngOnDestroy
lifecycle method like below :
ngOnDestroy() {
this.subscription.unsubscribe();
}
来源:https://stackoverflow.com/questions/59543013/using-ionic-4-trying-to-give-an-exit-alert-message-to-the-user-before-the-app-ge