Using ionic 4,Trying to give an exit alert message to the user before the app gets closed using hardware back button press event

痴心易碎 提交于 2020-01-16 19:38:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!